Sign in Go Pro


RxJava defer - Converting slow methods into an Observable

This lesson is for PRO members.

Upgrade today to get access to all the PRO lessons.

Unlock this lesson

Up next




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.

Summary of Content:

  • Description of problem; how to convert a long running operation into an RxJava Observable using defer
  • How to convert a simulated "read database" operation into an Observable
  • How to create an Observable using defer()
  • 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 defer

Code Links:

Other Relevant Links:




Will you please explain why in spite of using SubscribeOn( that heavy operation is not working on the io thread?

Thank you.

Hi Farhan, good question.

I assume your question is about the code at the ~3m 20s mark, where it's showing Observable.just(Database.readValue()) ?

The reason that doesn't work is, despite having subscribeOn( afterwards, the Observable.just(Database.readValue()) command is executed immediately in the current thread; the current thread being the main thread in this instance.

This code doesn't work as the heavy operation actually happens during the creation of the Observable. Once you have the Observable created, you'll be able to switch schedulers, but the creation of the Observable will happen immediately on the current thread (which is the main thread in the example).

Thank you for your answer. :)

I have found an another answer:

Thank you


Lessons in RxJava