本文介绍了如何在 RxSwift 中观察对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 Forecast
类:
class Forecast {
let city: City
var currentTemperature: String {
didSet {
print("cur tepm was set to \(currentTemperature)")
}
}
init(city: City) {
self.city = city
self.currentTemperature = "0"
}
func loadForecast() {
self.currentTemperature = "+10"
}
}
我正在尝试观察 ForecastViewModel
class ForecastViewModel {
fileprivate let variableForecast: Variable<Forecast>
var navigationTitle: Observable<String> {
return Observable.just("No name")
}
init(forecast aForecast: Forecast) {
self.variableForecast = Variable(aForecast)
self.variableForecast.asObservable().subscribe(onNext: { (s) in
print(s.currentTemperature)
})
variableForecast.value.currentTemperature = "-15"
variableForecast.value.loadForecast()
}
}
然而,subscribe on next 中的代码只执行一次并打印 0.didSet
块每次都会被调用.
However, code in subscribe on next is executed only once and prints 0. didSet
block is called every time.
我应该如何观察这个类的属性?
How should I observe a property of this class?
推荐答案
实际上你应该将 currentTemperature
声明为 Variable
来观察值的变化.你的Forecast
会变成这样
Actually you should declare currentTemperature
as Variable
to observe the value changes. Your Forecast
will become as this
class Forecast {
let city: City
var currentTemperature: Variable<String> = Variable("0")
init(city: City) {
self.city = city
}
func loadForecast() {
self.currentTemperature.value = "+10"
}
}
现在你可以订阅收听currentTemperature
的变化,如下所示,
So now you can subscribe to listen the changes in currentTemperature
as below,
class ForecastViewModel {
fileprivate let variableForecast: Variable<Forecast>
var navigationTitle: Observable<String> {
return Observable.just("No name")
}
init(forecast aForecast: Forecast) {
self.variableForecast = Variable(aForecast)
self.variableForecast.value.currentTemperature.asObservable().subscribe(onNext: { (value) in
print(value)
})
variableForecast.value.currentTemperature.value = "-15"
variableForecast.value.loadForecast()
}
}
这篇关于如何在 RxSwift 中观察对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!