0rt
0rt

Reputation: 1365

How to observe object's property in RxSwift?

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?

Upvotes: 3

Views: 8142

Answers (1)

Kamran
Kamran

Reputation: 15238

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

}

Upvotes: 1

Related Questions