Skip to content

Instantly share code, notes, and snippets.

@castasat
Created November 19, 2018 22:49
Show Gist options
  • Save castasat/d10857bf742717bb53390a744eb0b6cd to your computer and use it in GitHub Desktop.
Save castasat/d10857bf742717bb53390a744eb0b6cd to your computer and use it in GitHub Desktop.
Observe any object variable value change with RxJava2 PublishSubject wrapper written in Java
package net.cargo.reactive;
import android.support.annotation.Nullable;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
import static net.cargo.application.Cargo.check;
/**
* Usage:
*
* final T initialValue = 0; // T - any object type
*
* Variable<T> myValue = new Variable(initialValue);
*
* myValue
* .subject()
* .subscribe(otherValue ->
* changeValue(otherValue));
*
* myValue.set(1);
* myValue.set(2);
* myValue.set(3);
*
* final T lastValue = myValue.get(); // lastValue = 3
*
**/
public class
Variable<T>
{
// fields
PublishSubject<Variable<T>> subject;
T value;
public
Variable(){}
public
Variable(@Nullable final
T value)
{
if(check(value,
"value in " +
"Variable.constructor"))
{
subject =
PublishSubject.create();
set(value);
}
}
public final void
set(@Nullable final
T value)
{
if(check(value,
"value in " +
"Variable.set"))
{
this.value = value;
}
subject =
initializeVariableObservable(subject);
if(check(subject,
"subject in " +
"Variable.set"))
{
subject
.onNext(this);
}
}
@Nullable
public final T
get()
{
T result = null;
if(check(value,
"value in " +
"Variable.get"))
{
result = value;
}
return result;
}
@Nullable
public final Observable<Variable<T>>
subject()
{
Observable<Variable<T>> result = null;
subject =
initializeVariableObservable(subject);
if(check(subject,
"subject in " +
"Variable.subject"))
{
result = subject;
}
return result;
}
@Nullable
private PublishSubject<Variable<T>>
initializeVariableObservable(@Nullable final
PublishSubject<Variable<T>> subject)
{
PublishSubject<Variable<T>> result = null;
final PublishSubject<Variable<T>>
variablePublishSubject =
(subject == null)
? PublishSubject.create()
: subject;
if(check(variablePublishSubject,
"variablePublishSubject in " +
"Variable.initializeVariableObservable"))
{
result = variablePublishSubject;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment