Skip to content

Commit

Permalink
Add EventStreams.animationTicks() and FPSDemo.
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasMikula committed Feb 8, 2015
1 parent b136ffe commit 92c5306
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
32 changes: 32 additions & 0 deletions reactfx-demos/src/main/java/org/reactfx/demo/FPSDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.reactfx.demo;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import org.reactfx.EventStreams;

public class FPSDemo extends Application {

@Override
public void start(Stage primaryStage) {
Label label = new Label();

EventStreams.animationTicks()
.latestN(100)
.map(ticks -> {
int n = ticks.size() - 1;
return n * 1_000_000_000.0 / (ticks.get(n) - ticks.get(0));
})
.map(d -> String.format("FPS: %.3f", d))
.feedTo(label.textProperty());

primaryStage.setScene(new Scene(new StackPane(label), 250, 150));
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}
}
23 changes: 23 additions & 0 deletions reactfx/src/main/java/org/reactfx/EventStreams.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.function.Function;
import java.util.function.Supplier;

import javafx.animation.AnimationTimer;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.value.ChangeListener;
Expand Down Expand Up @@ -327,6 +328,28 @@ protected Subscription observeInputs() {
};
}

/**
* Returns an event stream that emits a timestamp of the current frame in
* nanoseconds on every frame. The timestamp has the same meaning as the
* argument of the {@link AnimationTimer#handle(long)} method.
*/
public static EventStream<Long> animationTicks() {
return new EventStreamBase<Long>() {
private final AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
emit(now);
}
};

@Override
protected Subscription observeInputs() {
timer.start();
return timer::stop;
}
};
}

/**
* Returns an event stream that emits all the events emitted from any of
* the {@code inputs}. The event type of the returned stream is the nearest
Expand Down

0 comments on commit 92c5306

Please sign in to comment.