rx.javafx.sources.ObservableSetSource Maven / Gradle / Ivy
package rx.javafx.sources;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import rx.Observable;
import rx.schedulers.JavaFxScheduler;
import rx.subscriptions.JavaFxSubscriptions;
public final class ObservableSetSource {
private ObservableSetSource() {}
public static Observable> fromObservableSet(final ObservableSet source) {
return Observable.create((Observable.OnSubscribe>) subscriber -> {
SetChangeListener listener = c -> subscriber.onNext(source);
source.addListener(listener);
subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener)));
}).startWith(source).subscribeOn(JavaFxScheduler.getInstance());
}
public static Observable fromObservableSetAdds(final ObservableSet source) {
return Observable.create((Observable.OnSubscribe) subscriber -> {
SetChangeListener listener = c -> {
if (c.wasAdded()) {
subscriber.onNext(c.getElementAdded());
}
};
source.addListener(listener);
subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener)));
}).subscribeOn(JavaFxScheduler.getInstance());
}
public static Observable fromObservableSetRemovals(final ObservableSet source) {
return Observable.create((Observable.OnSubscribe) subscriber -> {
SetChangeListener listener = c -> {
if (c.wasRemoved()) {
subscriber.onNext(c.getElementRemoved());
}
};
source.addListener(listener);
subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener)));
}).subscribeOn(JavaFxScheduler.getInstance());
}
public static Observable> fromObservableSetChanges(final ObservableSet source) {
return Observable.create((Observable.OnSubscribe>) subscriber -> {
SetChangeListener listener = c -> {
if (c.wasRemoved()) {
subscriber.onNext(new SetChange(c.getElementRemoved(), Flag.REMOVED));
}
if (c.wasAdded()) {
subscriber.onNext(new SetChange(c.getElementAdded(), Flag.ADDED));
}
};
source.addListener(listener);
subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener)));
}).subscribeOn(JavaFxScheduler.getInstance());
}
}