Jack Guo
Jack Guo

Reputation: 4664

RxJava how to cache static observable

I want to cache the following observable

val currentUser: Observable<User>
    get() = Observable.create { emitter ->
            ...
    }

Since the observable returned by create is static, I can't just call cache on it. The reason I am doing this is that the observable is accessed in different parts of the app, and I want it to immediately return the latest value, instead of making network calls every time.

Upvotes: 1

Views: 257

Answers (2)

Jack Guo
Jack Guo

Reputation: 4664

Thanks to EpicPandaForce, this is what I ended up using. I had to specify the emitter type otherwise there's error

val currentUser: Observable<User> = Observable.create { emitter: ObservableEmitter<User> ->
    ...
}.replay(1)
 .autoConnect(0)

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81539

Have you tried:

val currentUser: Observable<User> = Observable.create { emitter ->
    ...
}.replay(1)
 .autoConnect(0)

?

Upvotes: 2

Related Questions