Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create caching/hot version of rx.Single?

Tags:

The RxJava v1.0.13 introduced new type of an Observable: rx.Single. It fits great the request-response model but lacks the standard side-effects introducing operators like doOnNext(). So, it's much harder to make multiple things happen as a result.

My idea was to replace doOnNext() with multiple subscriptions to the same Single instance. But this can cause the underlaying work to be done multiple times: once per every subscription.

Example rx.Single implementation:

private class WorkerSubscribe<SomeData>() : Single.OnSubscribe<SomeData> {
    override fun call(sub: SingleSubscriber<in SomeData>) {
        try {
            val result = fetchSomeData()
            sub.onSuccess(result)
        } catch(t: Throwable) {
            sub.onError(t)
        }
    }
}

val single = Single.create<SomeData>(WorkerSubscribe())

Usage:

single.subscribe({}, {})
single.subscribe({}, {})   // Data is fetched for the second time

Is it possible to create a instance of Single that will not fetchSomeData() multiple times even when single.subscribe() is called multiple times, but cache and return the same result?

like image 314
atok Avatar asked Aug 07 '15 10:08

atok


People also ask

What is single RxJava2?

Single is an Observable which only emits one item or throws an error. Single emits only one value and applying some of the operator makes no sense.

What is Java Single as()?

Single behaves similarly to Observable except that it can only emit either a single successful value or an error (there is no onComplete notification as there is for an Observable ).

What is single in RxJava Android?

Advertisements. The Single class represents the single value response. Single observable can only emit either a single successful value or an error. It does not emit onComplete event.


1 Answers

You need RxJava Subject: BehaviorSubject or AsyncSubject

like image 127
Sergey Mashkov Avatar answered Oct 21 '22 02:10

Sergey Mashkov