A Lesson by Craig Russell
This lesson describes how you can easily take any expensive method and wrap the call inside an RxJava Observable using the defer() operator.
We describe Observable.defer() 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.defer() and Observable.just() together 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() on its own can’t help us solve this problem.
In this lesson you will learn:
- Description of problem; how to convert a long running operation into an RxJava Observable using
- How to convert a simulated “read database” operation into an
- How to create an
defer()lets you wrap an expensive method call
- The expensive method call will only happen when something subscribes
- Example project reading a value from a database, done with the use of
defer(), to do the read in a background thread.
- How to handle exceptions when using
Code for the Lesson
Pro members: Log in to view the code for this lesson!
Lessons in this course
- RxJava 2 – compose() Operator
- RxJava 2 – Disposing of Subscriptions with Disposable
- RxJava Operators – Observable.just()
- 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