如何在RxSwift中观察对象的属性?

时间:2018-06-23 19:08:40

标签: swift rx-swift

我有以下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"
    }

}

我正在尝试观察currentTemperatureforecast对象的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块。

我应该如何观察此类的属性?

1 个答案:

答案 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()
    }

}