Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only one value from Observable

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?

like image 739
beseder Avatar asked Nov 04 '25 07:11

beseder


1 Answers

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)
    }
}
like image 168
Evgeny Sureev Avatar answered Nov 06 '25 04:11

Evgeny Sureev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!