May be,

I hava a Maybe<> source and some kind of action that I want to perform with this value, if possibly not empty:

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

but when possibly empty, I want to complete "completed":

 return Completable.complete(); 

How to make this switch: if maybe it’s not empty, get one terminated, otherwise another?

+5
source share
1 answer

Well, I wrote two tests, and I think that this behavior you want to get out of the box. Perhaps the test will be completed without calling saveToDb. Perhaps Test2 will call saveToDb and smooth the value back and exit.

 @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(); } 
+10
source

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


All Articles