dudi
dudi

Reputation: 5732

How to observe a boolen field with RxJava

In my class Foo I have a boolen field. When the field changes I will react on this change in my class Bar How can I implement this with RxJava in Android?

Upvotes: 0

Views: 396

Answers (1)

Andrey Danilov
Andrey Danilov

Reputation: 6602

I guess you have to create class Foo with subject inside

class Foo {
    var booleanField: Boolean = false
    set(value) {
        field = value
        observable.onNext(value)
    }
    val observable = BehaviorSubject.createDefault(booleanField)
}

Then you have to observe that subject inside Boo class

class Boo(val observable: BehaviorSubject<Boolean>) {
    var booleanField: Boolean = false
    var disposable: Disposable? = null

    fun startObserve() {
        disposable?.dispose()
        disposable = observable.subscribe {
            booleanField = it
        }
    }

    fun finishObserve() {
        disposable?.dispose()
        disposable = null
    }
}

If you have to run it just create Foo and pass it's subject to Boo:

val foo = Foo()
val boo = Boo(foo.observable)
boo.startObserve()

foo.booleanField = true //boo is changed to true too

now if you change foo.booleanField, boo.booleanField will change too. If you need, you can run startObserve in constructor to start it immidiatly after creating instance. May be you have to create BehaviorSubject somewhere else and just pass to both classes using DI. And do not forget to unsubscribe after work is done.

Upvotes: 1

Related Questions