2

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!

b.lyte
  • 6,518
  • 4
  • 40
  • 51

1 Answers1

7

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();
akarnokd
  • 69,132
  • 14
  • 157
  • 192