Last active
April 23, 2016 17:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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