A FREE Lesson by Craig Russell
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.
In this lesson you will learn:
- How to convert a simulated “read database” operation into an
Observable.from()doesn’t solve this problem
- How to create an
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.
Watch the Full Lesson for FREE Now
Code for the Lesson
Lessons in this course
- RxJava: fromCallable vs defer – The differences between the two operators
- RxJava Operators – defer()
- RxJava Marble Diagrams
- RxJava fromCallable – Converting slow methods into an Observable
- RxJava Operators – observeOn
- RxJava Operators – subscribeOn
- Retrofit 2 with RxJava
- Grokking RxJava’s Observable.amb Operator
- Understanding the RxJava Observable.zip Operator
- RxJava Error Handling with Observable.error()
- Introduction to RxJava for Android Developers