Skip to content

Instantly share code, notes, and snippets.

@RaviH
Created October 28, 2015 23:05
Show Gist options
  • Save RaviH/cf662d60559fce30a4a4 to your computer and use it in GitHub Desktop.
Save RaviH/cf662d60559fce30a4a4 to your computer and use it in GitHub Desktop.
Observable Switch If Empty
package com.charter.aesd.deviceactivation.edgeservice.rest;
import rx.Observable;
import rx.functions.Func1;
import java.util.Optional;
/**
* Created by rhasija on 10/28/15.
*/
public class ObservableTest {
public static void main(String[] args) {
newStuff();
}
private static void newStuff() {
final Observable<Optional<Integer>> observable1 = Observable.just(Optional.empty());
final Observable<Optional<Integer>> observable2 = Observable.just(Optional.of(2));
final Observable<Optional<Integer>> observable3 = Observable.just(Optional.of(3));
System.out.println(observable1.switchIfEmpty(observable2).switchIfEmpty(observable3).toBlocking().single());
System.out.println(fooBar(observable1).switchIfEmpty(fooBar1(observable2)).toBlocking().single());
}
private static Observable<Integer> fooBar(Observable<Optional<Integer>> observable1) {
return observable1.flatMap(integer -> {
if (integer.isPresent()) {
return Observable.just(integer.get());
} else {
return Observable.empty();
}
});
}
private static Observable<Integer> fooBar1(Observable<Optional<Integer>> observable1) {
return observable1.flatMap(integer -> {
if (integer.isPresent()) {
return Observable.just(integer.get());
} else {
return Observable.empty();
}
});
}
private static void oldStuff() {
final Observable<Optional<Integer>> observable1 = Observable.just(Optional.of(1));
final Observable<Optional<Integer>> observable2 = Observable.just(Optional.of(2));
final Observable<Optional<Integer>> observable3 = Observable.just(Optional.of(3));
final Optional<Integer> single = observable1.flatMap(integer -> {
if (integer.get() != 1) {
return Observable.just(integer);
} else {
return observable2;
}
}).flatMap(integer -> {
if (integer.get() != 2) {
return Observable.just(integer);
} else {
return observable3;
}
}).toBlocking().single();
if (single.get() == 3) {
System.out.println("PASSED");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment