I am starting in RxSwift, coming from ReactiveCocoa. I have a conceptual question.
Let's say I have a value I want to observe over time, e.g. a temperatue. So there are many cases and places I subscribe this value to react on changes. No problem!
But there are also use cases when I just need the latest value e.g.:
if temperatue > 5 {
// do something
}
So i just want to do a decision/operation on that value or at least based on that value. That drives me close to using a shareReplay observable. But would I need to subscribe that value even when I just want to use it once?
Or is this approach wrong at all? How would I do that use case (value over time vs. accessing last value only once)? Would I need to sources, one hot one cold?
Use Variable:
class SomeClass {
let temperature = Variable<Int>(50)
func doSomething() {
if temperature.value > 50 {
print("something")
}
}
func subscribeToTemperature() {
temperature.asObservable.subscribeNext { t in
print("Temperature now is \(t)")
}.addDisposableTo(bag)
}
func setTemperature() {
temperature.value = 20
}
func observeTemperature(t: Observable<Int>) {
t.bindTo(temperature).addDisposableTo(bag)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With