BehaviorSubject subject.value is not set immediately after onNext
See original GitHub issueHello, I have been using Reaktive since a week and saw that BehaviorSubject sets value (_value) in onBeforeNext which is called some point later when serializer calls onSerializedValue Is this expected behavior?
The problem I am facing is, I am using BehaviorSubject to store some state and immediately after onNext if I read the value it does not reflect the latest value and wrong value is being set again. (PS: I am using this in Store in Mvi pattern but my State is global like Redux app) I am making sure that only one thread is allowed to read and write to store’s state (Stored in behavior subject) still I end up getting wrong state due to this behavior. Currenly I am using below workaround.
class Store(initialState: GlobalState): StoreInterface, DisposableScope by DisposableScope() {
private val subject = BehaviorSubject(initialState)
private var currentState: GlobalState = initialState
override fun getState(): GlobalState {
// FIXME: 18/09/20
// subject.value does not give latest value if called immediately after onNext so maintaining separate var
// return subject.value
return currentState
}
override fun setState(newState: GlobalState) {
currentState = newState
subject.onNext(newState)
}
override fun subscribe(observer: ObservableObserver<GlobalState>) {
subject.subscribe(observer)
}
}
If BehaviorSubject is indeed correct as per Rx specifications, can you suggest any better workaround to the issue? If DefaultSubject can be made public then also we can make our own custom Subject where value can be set in onNext itself rather than onBeforeNext
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
Hello. BehaviourSubject sets its value before calling subscribers. The only case when it won’t set the value immediately is when you call onNext recursively, while previous value is being emitted. The latter looks like a bug. I will check this and fix is needed. Thanks.
Closing this one. Feel free to reopen if there are any questions.