Reputation: 6249
A comment of Shai to my previuos question Codename One - Avoid screen size change on Android on app startup suggested me this new question:
In which cases a sleep is fine? I refert to the usage of TestUtils.waitFor()
without risking a kill of the app.
For example, if I've already shown a Form and I want to show it for at least an half second, so I insert a sleep before showing the next Form, is it ok?
I mean:
startForm.addShowListener(e -> {
startForm.setTransitionOutAnimator(CommonTransitions.createFade(1000));
TestUtils.waitFor(500);
nextForm.show();
});
startForm.show();
Upvotes: 2
Views: 165
Reputation: 52770
Wait for is clever as it sleeps "properly" on the EDT unlike Thread.sleep()
etc.:
public static void waitFor(final int millis) {
if(verbose) {
log("waitFor(" + millis + ")");
}
if(Display.getInstance().isEdt()) {
Display.getInstance().invokeAndBlock(new Runnable() {
public void run() {
try {
Thread.sleep(millis);
} catch (InterruptedException ex) {
}
}
});
} else {
try {
Thread.sleep(millis);
} catch (InterruptedException ex) {
}
}
}
However, if you invoke sleep within one of the "problematic" life cycle methods you might be risking things. E.g. init/start/constructor etc. must complete otherwise the native OS thread assumes the app didn't start. The same is true for the stop method which is invoked by the OS where there is an expectation of completion within a very short time frame.
Other than that we mostly hide the native OS thread complexities so a version of sleep that respects the EDT "should" work. The one exception I can think of is the browser navigation callback which explicitly exposes the native OS thread.
Upvotes: 1