RxJava Single.just() vs Single.fromCallable()?

You should use fromCallable() when you have a function like

MyObject myFunction() {
    // some login here
    return new MyObject();
}

Then you can create Single from this function like this:

Single.fromCallable(() -> myFunction());

Single.just(myObject) just emits your object without any logic.

So there is no need to use fromCallable() when you want to emit specific item.


Usually you will notice the difference when the thing you're emitting is not just an object but actually a result of some method calls that involve either heavy computation, I/O, or state.

Single.just(x) evaluates the x immediately in the current thread and then you're left with whatever was the result of x, for all subscribers.

Single.fromCallable(y) invokes the y callable in the subscribeOn scheduler at the time of subscription and separately for each subscriber.


So for example, if you wanted to offload an I/O operation to a background thread, you'd use

Single.fromCallable(() -> someIoOperation()).
    subscribeOn(Schedulers.io()).
    observeOn(AndroidSchedulers.mainThread()).
    subscribe(value -> updateUi(value), error -> handleError(error));

Having Single.just() here would not work since someIoOperation() would be executed on the current thread.


In the use case you've mentioned, there is actually no major difference.

Now imagine we need the object to be created dynamically through a function call?

fun getTimeObject() {
    val timeInMillis = System.currentTimeMillis()
    return TimeObject(timeInMillis)
}

Then with, Single.just(getTimeObject()) the resulting Single will emit the same Long when it has a new subscriber.

However, with Single.fromcallable(()-> getTimeObject()), the resulting Single will emit a different Long indicating the current time in millis when it has a new subscriber.

That's because fromCallable executes it's lambda everytime it has a new subscriber Lazily.