Understanding RxJava Create and fromCallable Operator

In this blog, we are going to learn the RxJava Create and fromCallable Operators. We will understand when to use the Create operator and when to use the fromCallable operator depending on our use-case. Most of the time, we do mistake while using RxJava Operators. Let's understand it clearly to avoid the mistake.

We will learn the following operators with examples.

  • Create
  • fromCallable

Create Operator of RxJava

Create Operator: create an Observable from scratch by means of a function.

Using Create Operator, we can do a task and keep emitting values one by one and finally completes. Let's see with an example

Observable.create<String> { emitter ->
    // do something and emit first item
    if (!emitter.isDisposed) {
        emitter.onNext("One")
    }
    // do something and emit second item
    if (!emitter.isDisposed) {
        emitter.onNext("Two")
    }
    // on complete
    if (!emitter.isDisposed) {
        emitter.onComplete()
    }
}
.subscribeOn(Schedulers.io())
.subscribe { item ->
    Log.d("CreateExample", "item : $item")
}

It will print "One" and "Two".

fromCallable Operator of RxJava

fromCallable Operator: Create an Observable from scratch but can emit only one item means fromCallable return an item.

Using fromCallable, we can do a task and can emit only one item. Let's see with an example

Observable.fromCallable<String> {
    // do something and return
    return@fromCallable "MindOrks"
}
.subscribeOn(Schedulers.io())
.subscribe { item ->
    Log.d("FromCallableExample", "item : $item")
}

It will print "MindOrks".

This does not mean that fromCallable is like Single. We will see later how it actually differs.

Both Create and fromCallable defer the execution of the task we specify until an observer subscribes to the ObservableSource. Means, it makes the task "lazy."

So, the following are the major differences between Create and fromCallable Operators:

  • Create can emit multiple items whereas fromCallable can emit only one item.
  • There is no simple way to check if isDisposed in fromCallable as persent in Create. So if it emits item after disposal, the throwable is delivered to the global error handler via RxJavaPlugins.onError as UndeliverableException. It means it will crash the application. This is how it is different from Single.

This way we can use RxJava Create and fromCallable Operators to solve the interesting problem.

Find the complete project here and learn RxJava.

Happy Learning :)

Team MindOrks

Also, Let’s become friends on Twitter, Linkedin, Github, Quora, and Facebook.