Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe to Completable

I hava a Maybe<> source and some action that I want to execute with this value if maybe is not empty:

// Maybe<T> maybe();
// Completable action(T value);
return maybe().flatMapCompletable(val -> action(val));

but when maybe is empty I want to get 'completed' completable:

return Completable.complete();

How to make this switch: if maybe is not empty get one completable, otherwise another?

like image 359
Kirill Avatar asked Apr 18 '17 11:04

Kirill


1 Answers

Well, I have written two tests, and I think this behaviour you want is given out of the box. The maybeTest will complete without calling saveToDb. maybeTest2 will call saveToDb and flatten the value back and complete.

@Test
public void maybeTest() throws Exception {
    Completable completable = Maybe.<Integer>empty()
            .flatMapCompletable(o -> {
                System.out.println(o);

                return saveToDb(5);
            });

    completable.test().await().assertComplete();
}


@Test
public void maybeTest2() throws Exception {
    Completable completable = Maybe.just(5)
            .flatMapCompletable(o -> {
                System.out.println(o);

                return saveToDb(5);
            });

    completable.test().await().assertComplete();
}

private Completable saveToDb(long value) {
    return Completable.complete();
}
like image 120
Hans Wurst Avatar answered Oct 17 '22 09:10

Hans Wurst