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
- Lesson 151: RxJava Operators – defer()
- Lesson 148: RxJava Marble Diagrams
- Lesson 147: RxJava fromCallable – Converting slow methods into an Observable
- Lesson 142: RxJava Operators – observeOn
- Lesson 139: RxJava Operators – subscribeOn
- Lesson 68: Retrofit 2 with RxJava
- Lesson 21: Grokking RxJava’s Observable.amb Operator
- Lesson 20: Understanding the RxJava Observable.zip Operator
- Lesson 19: RxJava Error Handling with Observable.error()
- Lesson 17: Introduction to RxJava for Android Developers