org.reactfx.Subscription Java Examples

The following examples show how to use org.reactfx.Subscription. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SourceEditorController.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void handleTestOpenRequest(@NonNull LiveTestCase oldValue, @NonNull LiveTestCase newValue) {
    oldValue.commitChanges();

    if (!newValue.getSource().equals(nodeEditionCodeArea.getText())) {
        nodeEditionCodeArea.replaceText(newValue.getSource());
    }

    if (newValue.getLanguageVersion() == null) {
        newValue.setLanguageVersion(globalLanguageProperty().getValue().getDefaultVersion());
    }

    Subscription sub = Subscription.multi(
        ReactfxUtil.rewireInit(newValue.sourceProperty(), astManager.sourceCodeProperty()),
        ReactfxUtil.rewireInit(newValue.languageVersionProperty(), languageVersionUIProperty),
        () -> propertiesPopover.rebind(null)
    );

    newValue.addCommitHandler(t -> sub.unsubscribe());
}
 
Example #2
Source File: MapDynamicTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void test() {
    Var<Integer> src = Var.newSimpleVar(1);
    Var<UnaryOperator<Integer>> fn = Var.newSimpleVar(UnaryOperator.identity());
    Val<Integer> mapped = src.mapDynamic(fn);

    assertEquals(1, mapped.getValue().intValue());

    src.setValue(2);
    assertEquals(2, mapped.getValue().intValue());

    fn.setValue(i -> i + i);
    assertEquals(4, mapped.getValue().intValue());

    Subscription sub = mapped.observeChanges((obs, oldVal, newVal) -> {
        assertEquals(4, oldVal.intValue());
        assertEquals(8, newVal.intValue());
    });
    fn.setValue(i -> i * i * i);
    sub.unsubscribe();

    fn.setValue(null);
    assertTrue(mapped.isEmpty());
}
 
Example #3
Source File: SubscribeableContentsObsSetTest.java    From RichTextFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void adding_new_subscriber_when_list_has_contents_does_not_fire_change_event() {
    SubscribeableContentsObsSet<Integer> contentSet = new SubscribeableContentsObsSet<>();

    contentSet.add(1);
    contentSet.add(2);
    contentSet.add(3);

    SimpleBooleanProperty changeWasFired = new SimpleBooleanProperty(false);
    Subscription removeChangeListener = contentSet.addChangeListener(change -> changeWasFired.set(true));

    contentSet.addSubscriber(b -> Subscription.EMPTY);

    assertFalse(changeWasFired.get());

    // cleanup
    removeChangeListener.unsubscribe();
}
 
Example #4
Source File: Val.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static <T> Val<T> create(
        Supplier<? extends T> computeValue,
        EventStream<?> invalidations) {
    return new ValBase<T>() {

        @Override
        protected Subscription connect() {
            return invalidations.subscribe(x -> invalidate());
        }

        @Override
        protected T computeValue() {
            return computeValue.get();
        }
    };
}
 
Example #5
Source File: ReactfxUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Converts an event stream to a val, that always holds the latest
 * emitted value of the stream.
 */
public static <T> Val<T> latestValue(EventStream<T> values) {
    return new ValBase<T>() {
        private T currentVal;

        @Override
        protected Subscription connect() {
            return values.subscribe(t -> {
                currentVal = t;
                invalidate();
            });
        }

        @Override
        protected T computeValue() {
            return currentVal;
        }
    };
}
 
Example #6
Source File: SubscribeableContentsObsSetTest.java    From RichTextFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void adding_subscriber_and_later_removing_it_will_unsubscribe_from_all_elements() {
    SubscribeableContentsObsSet<BoxedProperty> contentSet = new SubscribeableContentsObsSet<>();

    List<Integer> storageList = new LinkedList<>();

    // when property is set to a new value, store the new value in storageList
    Subscription removeSubscriber = contentSet.addSubscriber(b -> b.intValues.subscribe(storageList::add));

    BoxedProperty box1 = new BoxedProperty(1);
    BoxedProperty box2 = new BoxedProperty(2);
    contentSet.add(box1);
    contentSet.add(box2);

    box1.addOne();
    box2.addOne();
    assertEquals(2, storageList.size());

    storageList.clear();
    removeSubscriber.unsubscribe();

    box1.addOne();
    box2.addOne();

    assertEquals(0, storageList.size());
}
 
Example #7
Source File: SubscribeableContentsObsSet.java    From RichTextFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public boolean add(E e) {
    Objects.requireNonNull(e, "Cannot add a null object to this list");
    if (map.containsKey(e)) {
        return false;
    }

    // optimize for our use cases; initial capacity may need to be changed in future versions
    List<Subscription> list = new ArrayList<>(1);
    subscribers.stream()
            .map(f -> f.apply(e))
            .forEach(list::add);
    map.put(e, list);
    invalidateSet();
    fireElementAdded(e);

    return true;
}
 
Example #8
Source File: DragAndDropUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Registers the given [source] javafx Node as a source for a drag
 * and drop even with {@link #NODE_RANGE_DATA_FORMAT} content.
 */
public static Subscription registerAsNodeDragSource(javafx.scene.Node source, Node data, DesignerRoot root) {
    source.setOnDragDetected(evt -> {
        // drag and drop
        Dragboard db = source.startDragAndDrop(TransferMode.LINK);
        ClipboardContent content = new ClipboardContent();
        content.put(NODE_RANGE_DATA_FORMAT, TextRange.fullLine(data.getBeginLine(), 10000));
        db.setContent(content);
        root.getService(DesignerRoot.IS_NODE_BEING_DRAGGED).setValue(true);
        evt.consume();
    });

    source.setOnDragDone(evt -> {
        if (evt.getDragboard().hasContent(NODE_RANGE_DATA_FORMAT)) {
            root.getService(DesignerRoot.IS_NODE_BEING_DRAGGED).setValue(false);
        }
    });

    return () -> source.setOnDragDetected(null);
}
 
Example #9
Source File: ListSizeTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void test() {
    ObservableList<Integer> list = FXCollections.observableArrayList();
    Val<Integer> size = LiveList.sizeOf(list);
    List<Integer> sizes = new ArrayList<>();
    Subscription sub = EventStreams.valuesOf(size).subscribe(sizes::add);
    list.add(1);
    list.addAll(2, 3, 4);
    assertEquals(Arrays.asList(0, 1, 4), sizes);

    sub.unsubscribe();
    sizes.clear();
    list.addAll(5, 6);
    assertEquals(Arrays.asList(), sizes);

    EventStreams.valuesOf(size).subscribe(sizes::add);
    list.addAll(7, 8);
    assertEquals(Arrays.asList(6, 8), sizes);
}
 
Example #10
Source File: RuleEditorsController.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void afterChildrenInit() {

    ReactfxUtil.subscribeDisposable(
        selectedEditorProperty(),
        // connect the currently selected rule to the global state of the app
        x -> {
            TestCreatorService localCreator = x.getService(DesignerRoot.TEST_CREATOR);
            TestCreatorService globalCreator = getService(DesignerRoot.TEST_CREATOR);
            return Subscription.multi(
                // it's downstream.connect(upstream)
                getService(DesignerRoot.LATEST_XPATH).connect(x.getService(DesignerRoot.LATEST_XPATH)),
                getService(DesignerRoot.TEST_LOADER).connect(x.getService(DesignerRoot.TEST_LOADER)),
                // those two channels forward messages in opposite directions
                localCreator.getAdditionRequests().connect(globalCreator.getAdditionRequests()),
                globalCreator.getSourceFetchRequests().connect(localCreator.getSourceFetchRequests())
            );
        });

    selectedEditorProperty().values().filter(Objects::nonNull)
                            .subscribe(it -> getService(DesignerRoot.TEST_LOADER).pushEvent(this, it.selectedTestCaseProperty().getOpt().map(LiveTestCase::unfreeze).orElse(null)));
}
 
Example #11
Source File: SyntaxHighlightingCodeArea.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public SyntaxHighlightingCodeArea() {
    // captured in the closure
    final EventHandler<WindowEvent> autoCloseHandler = e -> syntaxAutoRefresh.ifPresent(Subscription::unsubscribe);

    // handles auto shutdown of executor services
    // by attaching a handler to the stage responsible for the control
    Val.wrap(sceneProperty())
       .filter(Objects::nonNull)
       .flatMap(Scene::windowProperty)
       .values()
       .filter(Objects::nonNull)
        .subscribe(c -> c.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, autoCloseHandler));


    // prevent ALT from focusing menu
    addEventFilter(KeyEvent.KEY_PRESSED, e -> {
        if (e.isAltDown()) {
            e.consume();
        }
    });


    // Make TAB 4 spaces
    InputMap<KeyEvent> im = InputMap.consume(
        EventPattern.keyPressed(KeyCode.TAB),
        e -> replaceSelection("    ")
    );

    Nodes.addInputMap(this, im);
}
 
Example #12
Source File: LiveList.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static <E> Subscription observeChanges(
        ObservableList<E> list,
        Consumer<? super ListChange<? extends E>> observer) {

    return observeQuasiChanges(
            list, qc -> observer.accept(QuasiListChange.instantiate(qc, list)));
}
 
Example #13
Source File: OrElse.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected Subscription connect() {
    trySrc = true;
    Subscription sub1 = Val.observeInvalidations(src, obs -> {
        trySrc = true;
        invalidate();
    });
    Subscription sub2 = Val.observeInvalidations(other, obs -> {
        if(!trySrc) {
            invalidate();
        }
    });
    return sub1.and(sub2);
}
 
Example #14
Source File: JavaKeywordsAsyncDemo.java    From RichTextFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void start(Stage primaryStage) {
    executor = Executors.newSingleThreadExecutor();
    codeArea = new CodeArea();
    codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
    Subscription cleanupWhenDone = codeArea.multiPlainChanges()
            .successionEnds(Duration.ofMillis(500))
            .supplyTask(this::computeHighlightingAsync)
            .awaitLatest(codeArea.multiPlainChanges())
            .filterMap(t -> {
                if(t.isSuccess()) {
                    return Optional.of(t.get());
                } else {
                    t.getFailure().printStackTrace();
                    return Optional.empty();
                }
            })
            .subscribe(this::applyHighlighting);

    // call when no longer need it: `cleanupWhenFinished.unsubscribe();`

    codeArea.replaceText(0, 0, sampleCode);

    Scene scene = new Scene(new StackPane(new VirtualizedScrollPane<>(codeArea)), 600, 400);
    scene.getStylesheets().add(JavaKeywordsAsyncDemo.class.getResource("java-keywords.css").toExternalForm());
    primaryStage.setScene(scene);
    primaryStage.setTitle("Java Keywords Async Demo");
    primaryStage.show();
}
 
Example #15
Source File: LiveList.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static <E> Subscription observeQuasiChanges(
        ObservableList<? extends E> list,
        QuasiChangeObserver<? super E> observer) {
    if(list instanceof LiveList) {
        LiveList<? extends E> lst = (LiveList<? extends E>) list;
        return lst.observeQuasiChanges(observer);
    } else {
        ListChangeListener<E> listener = ch -> {
            QuasiListChange<? extends E> change = QuasiListChange.from(ch);
            observer.onChange(change);
        };
        list.addListener(listener);
        return () -> list.removeListener(listener);
    }
}
 
Example #16
Source File: Val.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static <T> Subscription observeChanges(
        ObservableValue<? extends T> obs,
        ChangeListener<? super T> listener) {
    if(obs instanceof Val) {
        return ((Val<? extends T>) obs).observeChanges(listener);
    } else {
        obs.addListener(listener);
        return () -> obs.removeListener(listener);
    }
}
 
Example #17
Source File: ValAsList.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected Subscription observeInputs() {
    return Val.observeChanges(underlying, (obs, oldVal, newVal) -> {
        if(oldVal == null) {
            assert newVal != null;
            fireElemInsertion(0);
        } else if(newVal == null) {
            assert oldVal != null; // superfluous, just for symmetry
            fireElemRemoval(0, oldVal);
        } else {
            fireElemReplacement(0, oldVal);
        }
    });
}
 
Example #18
Source File: EditableStyledDocument.java    From RichTextFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns an {@link EventStream} that emits each {@link RichTextChange} in {@link #multiRichChanges()}'s
 * emitted list.
 */
default EventStream<RichTextChange<PS, SEG, S>> richChanges() {
    return new EventStreamBase<RichTextChange<PS, SEG, S>>() {
        @Override
        protected Subscription observeInputs() {
            return multiRichChanges().subscribe(list -> list.forEach(this::emit));
        }
    };
}
 
Example #19
Source File: LiveList.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
default EventStream<QuasiListModification<? extends E>> quasiModifications() {
    return new EventStreamBase<QuasiListModification<? extends E>>() {
        @Override
        protected Subscription observeInputs() {
            return observeQuasiModifications(this::emit);
        }
    };
}
 
Example #20
Source File: SubscribeableContentsObsSet.java    From RichTextFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Subscribes to all current and future elements' internal changes in this set until either they are removed
 * or this subscriber is removed by calling {@link Subscription#unsubscribe() unsubscribe} on the function's
 * returned {@link Subscription}.
 */
public Subscription addSubscriber(Function<? super E, Subscription> subscriber) {
    Objects.requireNonNull(subscriber);
    subscribers.add(subscriber);

    List<E> keys = new ArrayList<>(map.keySet());
    keys.forEach(key -> {
        List<Subscription> otherSubs = map.get(key);
        Subscription sub = subscriber.apply(key);
        otherSubs.add(sub);
        map.put(key, otherSubs);
    });

    return () -> removeSubscriber(subscriber);
}
 
Example #21
Source File: LiveList.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static <E> EventStream<QuasiListChange<? extends E>> quasiChangesOf(
        ObservableList<E> list) {
    if(list instanceof LiveList) {
        LiveList<E> lst = (LiveList<E>) list;
        return lst.quasiChanges();
    } else {
        return new EventStreamBase<QuasiListChange<? extends E>>() {
            @Override
            protected Subscription observeInputs() {
                return LiveList.<E>observeQuasiChanges(list, this::emit);
            }
        };
    }
}
 
Example #22
Source File: SizeTracker.java    From Flowless with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static <T> Val<T> avoidFalseInvalidations(Val<T> src) {
    return new ValBase<T>() {
        @Override
        protected Subscription connect() {
            return src.observeChanges((obs, oldVal, newVal) -> invalidate());
        }

        @Override
        protected T computeValue() {
            return src.getValue();
        }
    };
}
 
Example #23
Source File: DesignerUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static Subscription updateProgressOnConsole(Supplier<Double> progressGetter) {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(() -> updateProgress(progressGetter.get()), 0, 100, TimeUnit.MILLISECONDS);

    return () -> {
        scheduler.shutdown();
        updateProgress(1.0);
        System.out.println("\r"); // delete
    };
}
 
Example #24
Source File: ControlUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Add a hook on the owner window. It's not possible to do this statically,
 * since at construction time the window might not be set.
 */
public static void subscribeOnWindow(javafx.scene.Node node,
                                     Function<Window, Subscription> hook) {
    ReactfxExtensions.dynamic(
        LiveList.wrapVal(Val.wrap(node.sceneProperty()).flatMap(Scene::windowProperty)),
        (w, i) -> hook.apply(w)
    );
}
 
Example #25
Source File: InvalidatedVal.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected Subscription connect() {
    return ReactfxUtil.modificationTicks(
        LiveList.wrapVal(base),
        otherTicks
    ).subscribe(it -> invalidate());
}
 
Example #26
Source File: AnimatedVal.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected Subscription connect() {
    oldValue = src.getValue();
    return Val.observeChanges(src, (obs, oldVal, newVal) -> {
        oldValue = getValue();
        Duration d = duration.apply(oldValue, newVal);
        transition.setDuration(d);
        transition.playFromStart();
    });
}
 
Example #27
Source File: SearchableTreeView.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Subscription subscribeKeyNav(int numResults, Var<Integer> curIdx, Node eventSource) {
    // Make TAB or F3 cycle forward,
    // SHIFT+TAB or SHIFT+F3 cycle backwards
    return EventStreams.eventsOf(eventSource, KeyEvent.KEY_RELEASED)
                       .filter(it -> it.getCode() == KeyCode.F3 || it.getCode() == KeyCode.TAB)
                       .subscribe(ke -> {
                           int offset = ke.isShiftDown() ? -1 : +1;
                           curIdx.setValue((curIdx.getValue() + offset) % numResults);
                           ke.consume();
                       });


}
 
Example #28
Source File: ReactfxUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Add a hook on the owner window. It's not possible to do this statically,
 * since at construction time the window might not be set.
 */
public static <T> Subscription subscribeDisposable(ObservableValue<@Nullable ? extends T> node,
                                                   Function<@NonNull ? super T, Subscription> subscriber) {
    return ReactfxExtensions.dynamic(
        LiveList.wrapVal(node),
        (w, i) -> subscriber.apply(w)
    );
}
 
Example #29
Source File: SmartTextFieldListCell.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public final void updateItem(T item, boolean empty) {
    super.updateItem(item, empty);

    if (isEmpty() || item == null) {
        setGraphic(null);
        textField = null;
        if (subscriber != null) {
            subscriber.unsubscribe();
            subscriber = Subscription.EMPTY;
        }
    } else {
        if (isEditing()) {
            if (textField != null) {
                textField.setText(extractEditable(item).getValue());
            } else {
                textField = getEditingGraphic(item);
            }
            setGraphic(textField);
        } else {
            textField = null;
            Pair<Node, Subscription> nodeAndSub = getNonEditingGraphic(item);

            setGraphic(nodeAndSub.getKey());
            if (subscriber != null) {
                subscriber.unsubscribe();
            }
            subscriber = nodeAndSub.getValue();
        }
    }
}
 
Example #30
Source File: ControlUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Add a hook on the owner window. It's not possible to do this statically,
 * since at construction time the window might not be set.
 */
public static void subscribeOnSkin(Control node,
                                   Function<Skin<?>, Subscription> hook) {
    ReactfxExtensions.dynamic(
        LiveList.wrapVal(node.skinProperty()),
        (w, i) -> hook.apply(w)
    );
}