Skip to content

Instantly share code, notes, and snippets.

@johncarl81
Last active May 3, 2016 04:01
Show Gist options
  • Save johncarl81/99a983d17472a44610c94c3b10f20121 to your computer and use it in GitHub Desktop.
Save johncarl81/99a983d17472a44610c94c3b10f20121 to your computer and use it in GitHub Desktop.
Testing BehaviorSubject
package test;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
/**
* @author John Ericksen
*/
public class RXTest3 {
private final static Retrofit RETROFIT = new Retrofit();
private final static BehaviorSubject<String> SUBJECT = BehaviorSubject.create();
private static class Retrofit {
Observable<String> getValueObservable(final String input){
return Observable.defer(new Func0<Observable<String>>() {
public Observable<String> call() {
return Observable.just("Test " + input);
}
});
}
}
private static Observable<String> getObservable(boolean update, String input) {
if(update) {
RETROFIT.getValueObservable(input)
.subscribe(new Action1<String>() {
public void call(String value) {
SUBJECT.onNext(value);
}
});
}
return SUBJECT;
}
public static void main(String[] args) throws InterruptedException {
Subscription one = getObservable(true, "1").subscribe(buildSubscriber("One"));
Subscription two = getObservable(false, "2").subscribe(buildSubscriber("Two"));
Thread.sleep(1000);
Subscription three = getObservable(true, "3").subscribe(buildSubscriber("Three"));
Thread.sleep(1000);
three.unsubscribe();
Subscription four = getObservable(false, "4").subscribe(buildSubscriber("Four"));
Thread.sleep(1000);
Subscription five = getObservable(true, "5").subscribe(buildSubscriber("Five"));
/*
Outputs:
One.onNext() => Test 1
Two.onNext() => Test 1
One.onNext() => Test 3
Two.onNext() => Test 3
Three.onNext() => Test 3
Four.onNext() => Test 3
One.onNext() => Test 5
Two.onNext() => Test 5
Four.onNext() => Test 5
Five.onNext() => Test 5
*/
}
private static Subscriber<String> buildSubscriber(final String name) {
return new Subscriber<String>() {
public void onCompleted() {
System.out.println(name + ".onCompleted()");
}
public void onError(Throwable throwable) {
System.out.println(name + ".onError()");
}
public void onNext(String value) {
System.out.println(name + ".onNext() => " + value);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment