6
votes

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.

1
I have an anwser about the operator to use to correctly emits your objects. However, I am not really sure about the cyclic inference. Can you post code of insertAndReturnNewUserObservable and the mMapper.map(...) just to be sure. Also, IMHO, returning null is a pretty bad idea. But I will give details in my answer after seeing your code ;)mithrop

1 Answers

13
votes

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);