Skip to content

Instantly share code, notes, and snippets.

@greghelton
Last active April 23, 2016 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greghelton/b085fffb536dc025503575921de0fe7c to your computer and use it in GitHub Desktop.
Save greghelton/b085fffb536dc025503575921de0fe7c to your computer and use it in GitHub Desktop.
RxJava example that shows how dependent data is dynamically updated when other data changes
package com.reactive.summing;
import com.reactive.helpers.RxHelpers;
import rx.Observable;
import rx.subjects.BehaviorSubject;
public class ReactiveSum {
private BehaviorSubject<Double> a = BehaviorSubject.create(0.0);
private BehaviorSubject<Double> b = BehaviorSubject.create(0.0);
private BehaviorSubject<Double> c = BehaviorSubject.create(0.0);
public ReactiveSum() {
Observable.combineLatest(a, b, (x, y) -> x + y).subscribe(c);
}
public double getA() {
return a.getValue();
}
public void setA(double a) {
this.a.onNext(a);
}
public Observable<Double> obsA() {
return a.asObservable();
}
public double getB() {
return b.getValue();
}
public void setB(double b) {
this.b.onNext(b);
}
public Observable<Double> obsB() {
return b.asObservable();
}
public double getC() {
return c.getValue();
}
public Observable<Double> obsC() {
return c.asObservable();
}
public static void main(String[] args) {
ReactiveSum sum = new ReactiveSum();
RxHelpers.subscribePrint(sum.obsC(), "Sum");
sum.setA(5);
sum.setB(4);
sum.setA(9);
sum.setB(0);
/* prints
main|Sum : 0.0
main|Sum : 5.0
main|Sum : 9.0
main|Sum : 13.0
main|Sum : 9.0
*/
}
}
package com.reactive.helpers;
import java.util.Arrays;
import java.util.stream.Collectors;
import rx.Observable;
import rx.Subscription;
public final class RxHelpers {
public static <T> Subscription subscribePrint(Observable<T> observable, String name) {
return observable.subscribe(
(v) -> System.out.println(Thread.currentThread().getName()
+ "|" + name + " : " + v), (e) -> {
System.err.println("Error from " + name + ":");
System.err.println(e);
System.err.println(Arrays
.stream(e.getStackTrace())
.limit(5L)
.map(stackEl -> " " + stackEl)
.collect(Collectors.joining("\n"))
);
}, () -> System.out.println(name + " ended!"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment