Getting error "Callable returned null" when using RxJava2

priyankvex picture priyankvex · May 3, 2017 · Viewed 10.4k times · Source

I am using RxJava2 in my android project.

I am using the following code to create the Observable

public Observable<AlbumDetails> loadAlbumFromAlbumId(final String albumId) {
    return Observable.fromCallable(new Callable<AlbumDetails>() {
        @Override
        public AlbumDetails call() throws Exception {
             AlbumDetails albumDetails = getAlbumDetails(albumId);     
             return albumDetails;   
       });
}

From the observable, I am getting following error in the onError method of DisposableObserver

Callable returned null

This didn't use to happend when using RxJava.

Answer

Martin Andersson picture Martin Andersson · Oct 25, 2018

I used to have code like this:

Observable<R> obs = Observable.fromCallable(this::work);

work() may return null and as you noted, RxJava 2 is not happy with this.

Method 1

Observable<R> obs = Maybe.fromCallable(this::work).toObservable();

In this way, the end consumer - the observer - will only kick off if work() had anything to return. If work() returned null then it's the same as subscribing to an empty Observer; nothing happens.

Method 2

Observable<R> obs = Observable.create(e -> {
    R r = work();

    if (r != null) {
        e.onNext(r);
    }

    e.onComplete();
});

Method 3:

Wrapping each emission in an Optional = bad idea for a number of reasons.

Mainly because I only use Optional in my APIs if it is expected and sort of the "normal" scenario that you get a null every now and then. If null is not expected or very rare, maybe as a direct result of another API call done by the same consumer, then I return null and let the consumer deal with it in these exceptional cases rather than having every consumer deal with Optional all over the place.