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 an async flow, then it is fine.
- Otherwise, ensure the lazy evaluation of the logic by
Single.defer(() -> doThing())
Or
Single.fromCallable(() -> doThing())
Comments
Post a Comment