Created
April 8, 2017 15:24
-
-
Save OleksandrKucherenko/b75d9c7bab7bd203877d58e870653fc9 to your computer and use it in GitHub Desktop.
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 **; // <-- add own package name | |
import android.support.annotation.Nullable; | |
import rx.Observable; | |
import rx.subjects.PublishSubject; | |
import rx.subjects.Subject; | |
/** Generic implementation of value/property that triggers subscribers on value change. */ | |
public class RxValue<T> { | |
/** Observable and an Observer of the value. */ | |
private final Subject<T, T> subject = PublishSubject.create(); | |
/** Last known value. */ | |
private T lastValue; | |
/** Is value in empty state or not. */ | |
private boolean isEmpty; | |
private RxValue() { | |
lastValue = null; | |
isEmpty = true; | |
} | |
/** Hidden constructor. */ | |
private RxValue(final T initialValue) { | |
lastValue = initialValue; | |
} | |
/** Static method for simplified instance creation. Less verbose syntax. */ | |
public static <T> RxValue<T> of(T initialValue) { | |
return new RxValue<>(initialValue); | |
} | |
/** Create rx value that does is empty from the beginning. */ | |
public static <T> RxValue<T> empty() { | |
return new RxValue<>(); | |
} | |
/** Get the current value. */ | |
@Nullable | |
public T value() { | |
return lastValue; | |
} | |
/** Set the instance to a new value. */ | |
public T set(final T value) { | |
if (isEmpty || value != lastValue) { | |
isEmpty = false; | |
lastValue = value; | |
if (subject.hasObservers()) { | |
subject.onNext(lastValue); | |
} | |
} | |
return value(); | |
} | |
/** Get instance of observable for triggering. */ | |
public Observable<T> asObservable() { | |
if (isEmpty) { | |
return subject; | |
} | |
return Observable.merge(Observable.just(lastValue), subject); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unit Tests