Created
October 28, 2015 23:05
-
-
Save RaviH/cf662d60559fce30a4a4 to your computer and use it in GitHub Desktop.
Observable Switch If Empty
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.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