How to create Observable that emits every time a m

2020-07-24 05:03发布

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!

1条回答
神经病院院长
2楼-- · 2020-07-24 05:14

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();
查看更多
登录 后发表回答