Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava - Using flatmap when return could be null

Tags:

java

rx-java

Let's use this class for the example:

 public static class CurrentUser{
    public static Observable<User> get(){
         //code basically returns the currently logged in User object
         //but sometimes there may not be a logged in user 
    }

    public static Observable<PutResult> logOut(){
        return get()

                //I only want to execute the following if user != null

                .flatMap(new Func1<User, Observable<PutResult>>() {
                    @Override
                    public Observable<PutResult> call(User user) {
                        //delete the session token and save
                        user.removeSessionToken();
                        return DatabaseModule.getStorIOSQLite()
                                .put()
                                .object(user)
                                .prepare()
                                .asRxObservable();
                    }
                });
    }

}

Should I just return null inside the flatmap? Are there any repercussions to this since it's expecting an Observable?

like image 447
Sree Avatar asked Feb 11 '16 17:02

Sree


2 Answers

You should not return null but Observable.empty() instead.

.flatMap(new Func1<User, Observable<PutResult>>() {
    @Override
    public Observable<PutResult> call(User user) {
        if (user == null) return Observable.empty();

        //delete the session token and save
        user.removeSessionToken();
        return DatabaseModule.getStorIOSQLite()
                .put()
                .object(user)
                .prepare()
                .asRxObservable();
    }
});
like image 90
knutwalker Avatar answered Oct 10 '22 06:10

knutwalker


It isn't clear what null you're talking about.

If you're asking whether the Observable<PutResult> can emit a PutResult that's null, then yes. This would result in a null being emitted by the outer observable.

If you're asking whether the Observable<PutResult> returned by the Func1 can be null, then no. Return Observable.empty() instead, (or Observable.just(null) or similar if you need to keep track of the number of emitted items).

like image 27
Malt Avatar answered Oct 10 '22 06:10

Malt