Last active
August 29, 2015 14:16
-
-
Save yongjhih/25017ac41efb4634c2ab to your computer and use it in GitHub Desktop.
Optional Observable
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
public class Optional<T> { | |
Observable<T> obs; | |
public Optional(Observable<T> obs) { | |
this.obs = obs; | |
} | |
public static <T> Optional<T> of(T value) { | |
if (value == null) { | |
throw new NullPointerException(); | |
} else { | |
return new Optional<T>(Observable.just(value)); | |
} | |
} | |
public static <T> Optional<T> ofNullable(T value) { | |
if (value == null) { | |
return empty(); | |
} else { | |
return new Optional<T>(Observable.just(value)); | |
} | |
} | |
public T get() { | |
return obs.toBlocking().single(); | |
} | |
public T orElse(T defaultValue) { | |
return obs.defaultIfEmpty(defaultValue).toBlocking().single(); | |
} | |
public <R> Optional<R> map(Func1<T, R> func) { | |
return Optional.ofNullable(func.call(get())); | |
} | |
public <R> Optional<R> flatMap(Func1<T, Optional<R>> func) { | |
return func.call(get()); | |
} | |
public static <T> Optional<T> empty() { | |
return new Optional<T>(Observable.empty()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment