RxJava Create and fromCallable Operator

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
RxJava Create and fromCallable Operator

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we are going to learn about 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 mistakes 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.

rxjava create

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.

rxjava fromcallable

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 "Amit"
}
.subscribeOn(Schedulers.io())
.subscribe { item ->
    Log.d("FromCallableExample", "item : $item")
}

It will print "Amit".

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 present 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.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.