How to observe object's property in RxSwift?

一个人想着一个人 提交于 2020-12-11 02:12:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!