RxJava - Using flatmap when return could be null
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();
}
});
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).
In RxJava 2 null is considered to be an invalid value. You can use Maybe component in those cases , some thing like the below
Maybe<Result>
or
You can use flatMapMaybe<Result>