Can we detect if a class member value is getting changed using RxJava?? Say in a class there is a variable var, now can we get notified whenever the value of var changes using RxJava.
Asked
Active
Viewed 9,159 times
2 Answers
18
You can use something like this:
private final BehaviorSubject<Integer> subject = BehaviorSubject.create();
private Integer value=0;
public Observable<Integer> getUiElementAsObservable() {
return subject;
}
public void updateUiElementValue(final Integer valueAdded) {
synchronized (value) {
if (valueAdded == 0)
return;
value += valueAdded;
subject.onNext(value);
}
}
and subscribe to it like this:
compositeSubscription.add(yourClass.getUiElementAsObservable()
.subscribe(new Action1<Integer>() {
@Override
public void call(Integer userMessage) {
setViews(userMessage,true);
}
}));
you have to create setter for all of your variables that you want something subscribe to their changes and call onNext if change applied.
UPDATE
When an observer subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable
you can see other type of subjects here: http://reactivex.io/documentation/subject.html
some useful link:
about reactive programming : https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
and about rxjava : https://youtu.be/k3D0cWyNno4

Siavash Abdoli
- 1,852
- 3
- 22
- 38
-
I am new to RxJava,So if you kindly explain it would be helpful – Debu Jul 05 '16 at 13:54
5
http://rxmarbles.com/#distinctUntilChanged
Code
Observable.just("A", "B", "B", "A", "C", "A", "A", "D")
.distinctUntilChanged()
.subscribe(abc -> Log.d("RXJAVA", abc));
Result
A
B
A
C
A
D

HJ Byun
- 61
- 1
- 2
-
this function is good for detection but with this code that write above, you have to know the value before subscribe. if you want emit something later you can't use this observable anymore – Siavash Abdoli Dec 05 '16 at 19:51
-
1actually the problem is with "just", not distinctUntilChanged function. – Siavash Abdoli Dec 05 '16 at 19:52
-
It may also be worth it to provide the BiPredicate comparer function as a parameter to distinctUntilChanged() depending on your use case. i.e. in Kotlin, Observable.just("A", "B", "B", "A", "C", "A", "A", "D") .distinctUntilChanged {string1: String, string2: String -> string1.equals(string2)} .subscribe(abc -> Log.d("RXJAVA", abc)); Otherwise it may be using string1 == string2 which many times may not be true – caitcoo0odes Feb 20 '19 at 00:06