Rx Kotlin/Java 状态可观察
Rx Kotlin/Java Observable on state
有什么方法可以创建 RxJava2 Observable
来通知状态更改?喜欢:
private var internalState = "state1"
val state: Observable<String> = Observable(...)
...
fun updateState(newState: String) { ... } // !!! attention: I need to notify all subscribers about this new state
然后在任何地方使用它,例如:
// observe on state
state.subscribe(...)
必须在每次状态更新时调用此订阅
经过一些研究:
val source = PublishSubject.create<String>()
var state = "state1"
get() = field // redundant: only to show it's possible to get state directly: maybe for class internal usages
set(value) {
field = value
source.onNext(field)
}
现在使用正常的 subscribe
或从 source
创建新的 Observable
source.subscribe(...)
有什么方法可以创建 RxJava2 Observable
来通知状态更改?喜欢:
private var internalState = "state1"
val state: Observable<String> = Observable(...)
...
fun updateState(newState: String) { ... } // !!! attention: I need to notify all subscribers about this new state
然后在任何地方使用它,例如:
// observe on state
state.subscribe(...)
必须在每次状态更新时调用此订阅
经过一些研究:
val source = PublishSubject.create<String>()
var state = "state1"
get() = field // redundant: only to show it's possible to get state directly: maybe for class internal usages
set(value) {
field = value
source.onNext(field)
}
现在使用正常的 subscribe
或从 source
Observable
source.subscribe(...)