Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava, execute observable only if first was empty

Tags:

java

rx-java

I want to insert a new user into my database only if a user with the same email does not exist.

Therefor I have two Observables: The first one emits a user with a specific email or completes without emitting anything. The second Observable inserts a new user and returns an Object of this newly created user.

My problem is, that I don't want the user emmitted by the first Observable (if existent) is transported to the Subscriber. Rather I would like to map it to null).

Observable<UserViewModel> observable = 
    checkAndReturnExistingUserObservable
        .map(existingUser -> null)
        .firstOrDefault(
            insertAndReturnNewUserObservable
                .map(insertedUser -> mMapper.map(insertedUser)
        )

This was the last thing I tried, but it says "cyclic inference" at the second map operator.

To summarize. I want to perform a second Observable only if the first completed empty but if not I don't want to return the Data emmitted by first rather I want to return null.

Any help is really appreciated.

like image 713
chris115379 Avatar asked Dec 10 '15 06:12

chris115379


1 Answers

There is the switchIfEmpty operator for this kind of operation:

checkAndReturnExistingUserObservable
.switchIfEmpty(insertAndReturnNewUserObservable)

Edit

If you don't need an existing user, there was a flatMap-based answer that turned the first check into a boolean value and dispatched based on its value:

checkAndReturnExistingUserObservable
.map(v -> true).firstOrDefault(false)
.flatMap(exists -> exists ? Observable.empty() : insertAndReturnNewUserObservable);
like image 118
akarnokd Avatar answered Nov 14 '22 23:11

akarnokd