Search code examples
javarx-java2memoizationreactivex

How do I memoize the value emitted by a Single?


Say I have an expensive calculation that creates an object. I want to give the caller some flexibility as to where that happens, with subscribeOn(). But I also don't want to make that calculation more than once, because of side effects (e.g. the object is backed by some external data store).

I can write

MyObject myObject = MyObject.createExpensively(params);
return Single.just(myObject);

but this does the expensive work on the calling thread.

I can write

Callable<MyObject> callable = () -> MyObject.createExpensively(params);
return Single.fromCallable(callable);

but this will invoke createExpensively() (with side effects) once per subscription, which isn't what I want if there are multiple subscribers.

If I want to ensure that createExpensively() is only called once, and its side effects only occur once, what's the pattern I'm looking for here?


Solution

  • You could use Single.cache():

    Single.fromCallable(() -> MyObject.createExpensively(params)).cache();