Sign in Go Pro

RxJava

RxJava fromCallable - Converting slow methods into an Observable

 

Up next

Previous

About

#Description This lesson describes how you can easily take any expensive method and wrap the call inside an `RxJava Observable.` Once you start using `RxJava`, you will want all slow methods to return an `Observable` to enable you to use all of the benefits of `RxJava`. However, this isn't always possible. Sometimes, you can't change what a method returns, but you still want to use the power of `RxJava`. This is a typical problem in working with legacy code. We describe `Observable.fromCallable()` and how we can use this to wrap any method in an `Observable` so that we can defer the execution of an expensive method until the correct time, and so that we can control which threads are used to execute the method. We provide an example project where we use `Observable.fromCallable()` to execute a slow method on a background thread and return the result on the Android main thread. We describe why simply using `Observable.just()` can't help us solve this problem. #Summary of Content: - How to convert a simulated "read database" operation into an `Observable` - Why `Observable.just()` and `Observable.from()` doesn't solve this problem - How to create an `Observable` using `Observable.fromCallable()` - `Observable.fromCallable()` lets you wrap an expensive method call - The expensive method call will only happen when something subscribes - How to clean up the syntax using Java 8 / Retrolambda - Example project reading a value from a database with the use of `fromCallable()` to do the read in a background thread. #Code Links: - [https://github.com/CDRussell/CasterRxJava](https://github.com/CDRussell/CasterRxJava) #Other Relevant Links: - [http://reactivex.io/documentation/operators/start.html](http://reactivex.io/documentation/operators/start.html) - [https://artemzin.com/blog/rxjava-defer-execution-of-function-via-fromcallable/](https://artemzin.com/blog/rxjava-defer-execution-of-function-via-fromcallable)

Instructor

Links

Lessons in RxJava