Rxjava2 - how to zip Maybe it can be empty?

I'm trying to make 3 calls Web services (eg getPhoneNumber, getFirstName, getLastName), and to collect responses in a shared object Person. Any of the web service calls can return Maybe.empty().

When you try to zipreply together, it rxjava2skips the zip operation and usually ends (without aggregating my response).

For a simplified example, see below:

@Test
public void maybeZipEmptyTest() throws Exception {
    Maybe<Integer> a = Maybe.just(1);
    Maybe<Integer> b = Maybe.just(2);
    Maybe<Integer> empty = Maybe.empty();

    TestObserver<String> observer = Maybe.zip(a,  b, empty, (x, y, e) -> {
        String output = "test: a "+x+" b "+y+" empty "+e;
        return output;
    })
    .doOnSuccess(output -> {
        System.out.println(output);
    })
    .test();

    observer.assertNoErrors();
}

How can we collect null values ​​in a zip operation instead of skipping / ignoring the zip operation? If this is the wrong model to solve this problem, how would you recommend to solve it?

+4
source share
1 answer

defaultIfEmpty - .

-, ( ), Java 8 Optional .

@Test
public void maybeZipEmptyTest() throws Exception {
    Maybe<Optional<Integer>> a = Maybe.just(Optional.of(1));
    Maybe<Optional<Integer>> b = Maybe.just(Optional.of(2));
    Maybe<Optional<Integer>> empty = Maybe.just(Optional.empty());

    TestObserver<String> observer = Maybe.zip(a,  b, empty, (x, y, e) -> {
        String output = "test: a "+toStringOrEmpty(x)+" b "+toStringOrEmpty(y)+" empty "+toStringOrEmpty(e);
        return output;
    })
    .doOnSuccess(output -> {
        System.out.println(output);
    })
    .test();

    observer.assertNoErrors();
}

private String toStringOrEmpty(Optional<Integer> value){
    if(value.isPresent()){
        return value.get().toString();
    }
    else { 
        return "";
    }
} 
+1

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


All Articles