|
| 1 | +package rx.schedulers; |
| 2 | + |
| 3 | +import javafx.application.Application; |
| 4 | +import javafx.event.ActionEvent; |
| 5 | +import javafx.scene.Scene; |
| 6 | +import javafx.scene.control.Button; |
| 7 | +import javafx.scene.control.Label; |
| 8 | +import javafx.scene.control.TextField; |
| 9 | +import javafx.scene.layout.GridPane; |
| 10 | +import javafx.stage.Stage; |
| 11 | +import rx.Observable; |
| 12 | +import rx.Subscription; |
| 13 | +import rx.observables.JavaFxObservable; |
| 14 | + |
| 15 | +public class RxJavaFXTest extends Application { |
| 16 | + |
| 17 | + private final Button incrementBttn; |
| 18 | + private final Label incrementLabel; |
| 19 | + private final Subscription sub1; |
| 20 | + |
| 21 | + private final TextField textInput; |
| 22 | + private final Label fippedTextLabel; |
| 23 | + private final Subscription sub2; |
| 24 | + |
| 25 | + public RxJavaFXTest() { |
| 26 | + |
| 27 | + //initialize increment demo |
| 28 | + incrementBttn = new Button("Increment"); |
| 29 | + incrementLabel = new Label(""); |
| 30 | + |
| 31 | + Observable<ActionEvent> bttnEvents = |
| 32 | + JavaFxObservable.fromNodeEvents(incrementBttn, ActionEvent.ACTION); |
| 33 | + |
| 34 | + sub1 = bttnEvents.map(e -> 1).scan(0,(x,y) -> x + y) |
| 35 | + .map(Object::toString) |
| 36 | + .subscribe(incrementLabel::setText); |
| 37 | + |
| 38 | + //initialize text flipper |
| 39 | + textInput = new TextField(); |
| 40 | + fippedTextLabel = new Label(); |
| 41 | + |
| 42 | + Observable<String> textInputs = |
| 43 | + JavaFxObservable.fromObservableValue(textInput.textProperty()); |
| 44 | + |
| 45 | + sub2 = textInputs.observeOn(Schedulers.computation()) |
| 46 | + .map(s -> new StringBuilder(s).reverse().toString()) |
| 47 | + .observeOn(JavaFxScheduler.getInstance()) |
| 48 | + .subscribe(fippedTextLabel::setText); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public void start(Stage primaryStage) throws Exception { |
| 53 | + |
| 54 | + GridPane gridPane = new GridPane(); |
| 55 | + |
| 56 | + gridPane.setHgap(10); |
| 57 | + gridPane.setVgap(10); |
| 58 | + |
| 59 | + gridPane.add(incrementBttn,0,0); |
| 60 | + gridPane.add(incrementLabel,1,0); |
| 61 | + |
| 62 | + gridPane.add(textInput,0,1); |
| 63 | + gridPane.add(fippedTextLabel, 1,1); |
| 64 | + |
| 65 | + Scene scene = new Scene(gridPane); |
| 66 | + primaryStage.setWidth(265); |
| 67 | + primaryStage.setScene(scene); |
| 68 | + primaryStage.show(); |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public void stop() throws Exception { |
| 73 | + super.stop(); |
| 74 | + |
| 75 | + sub1.unsubscribe(); |
| 76 | + sub2.unsubscribe(); |
| 77 | + } |
| 78 | +} |
0 commit comments