b.lyte
b.lyte

Reputation: 6737

How to create Observable that emits every time a member variable is updated (onCompleted never called)

I'd like to create an observable in a singleton class that manages state (i.e. it stores an auth token). I'd like my android app/activity to subscribe to an observable that will emit an update every time the state (auth token) is updated. How do I do this? All examples I've seen show how you can create a self contained observable that completes immediately or after subscription.

Thanks for your help!

Upvotes: 2

Views: 615

Answers (1)

akarnokd
akarnokd

Reputation: 69997

You need a BehaviorSubject.

BehaviorSubject<State> rxState = BehaviorSubject.create(initialState);

// update state
rxState.onNext(newState);

// observe current state and all changes after
rxState.subscribe(...);

If you want to set the state from multiple threads concurrently, you need this as the first line.

Subject<State, State> rxState = BehaviorSubject.create(initialState).toSerialized();

Upvotes: 7

Related Questions