Posts

Showing posts with the label single

Merging Rx Single Results

Today, I saw something incredible which basically looks like this. public class Thing { final ThingService thingService ; public Thing ( final ThingService thingService) { this . thingService = thingService ; } public Single<List<String>> getOtherThings ( final List<String> keys ) { return keys.stream() .map(key -> getOtherThing(key)) .reduce( Single. just (Collections. emptyList ()) , (singleThing1 , singleThing2) -> singleThing1 .flatMap(thing1 -> singleThing2 .map(thing2 -> { final List<String> newList = new LinkedList<>( thing1 ) ; newList.addAll(thing2) ; return newList ; })) ) ; } } public class ThingService { public Single<List<Strin...

Defer functions in Rx Single chain

Often you will see this usage of an Rx Single : Single. just (doThing())) So what problems does it have? To start with, unless the statement is the beginning of an async flow, then this would be fine. Otherwise, you are just asking for trouble, because it spins off an orphaned async flow which is not subscribed to . Secondly, this statement is often accompanied by the following usage: single.flatMap(thing -> Single. just (doThing(thing))) And that is just unnecessary , the correct way should be: single.map(thing -> doThing(thing)) Finally, the biggest issue with this approach is: it does not guarantee  re-evaluation of the async method, the logic will be evaluated once at the first run, even before it was subscribed. And even worse, if there is a retry policy configured, the retry will just pick up the same result every time, producing false results for the retries. But this problem is not unsolvable, there are two principles to consider: - If the code is the beginning of a...