RxJava, execute observables only if the first one was empty

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

For this, I have two observables: The first one emits a user with a specific email or ends without any changes. The second Observable inserts a new user and returns an object of this newly created user.

My problem is that I do not want the user sent by the first Observable (if exists) to be delivered to the subscriber. Rather, I would like to match it to zero).

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

This was the last thing I tried, but it says "loop output" in the second map statement.

Summarizing. I want to perform the second observation only if the first is empty, but if not, I do not want to return the data omitted by the first, but I want to return null.

Any help really appreciated.

+4
source share
1 answer

For an operation of this type, there is an operator switchIfEmpty:

checkAndReturnExistingUserObservable
.switchIfEmpty(insertAndReturnNewUserObservable)

Edit

If you do not need an existing user, there was a response based on flatMap, which turned the first check into a logical value and sent based on its value:

checkAndReturnExistingUserObservable
.map(v -> true).firstOrDefault(false)
.flatMap(exists -> exists ? Observable.empty() : insertAndReturnNewUserObservable);
+10
source

Source: https://habr.com/ru/post/1619309/


All Articles