我有以下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"
}
}
我正在尝试观察currentTemperature
中forecast
对象的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()
}
}
但是,next on上的代码仅执行一次并显示0。每次都调用didSet
块。
我应该如何观察此类的属性?
答案 0 :(得分:1)
实际上,您应该将currentTemperature
声明为Variable
来观察值的变化。您的Forecast
会变成这样
class Forecast {
let city: City
var currentTemperature: Variable<String> = Variable("0")
init(city: City) {
self.city = city
}
func loadForecast() {
self.currentTemperature.value = "+10"
}
}
因此,现在您可以订阅以监听currentTemperature
中的更改,如下所示,
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()
}
}