问题
I have the following Forecast
class:
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"
}
}
I am trying to observe currentTemperature
property of forecast
object in 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()
}
}
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?
回答1:
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"
}
}
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()
}
}
来源:https://stackoverflow.com/questions/51004283/how-to-observe-objects-property-in-rxswift