Rx Kotlin / Java可观察到的状态

时间:2018-07-13 18:13:27

标签: java android kotlin rx-java2 rx-kotlin2

是否可以创建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(...)

此订阅必须在每个状态更新时被调用

1 个答案:

答案 0 :(得分:0)

经过研究:

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或从Observable创建新的source

source.subscribe(...)