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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With