I have a for loop and structure like this:
for(....)
....
....
if(isTrue)
... do something..
.. method to be executed once (doTrick) is declared outside for loop.
....endif
endfor
public void doTrick()
...
...
..end
Is it possible for a method in for loop to be executed only once?
We can apply concepts similar to our debounce utility to execute a function once and only one time. function execOnce(fn, context) { var result; return function () { if (fn) { result = fn. apply(context || this, arguments); fn = null; } return result; }; } function sayHello() { console.
You can do this, by using shared preferences . Store a value in shared preferences: SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences. Editor editor = prefs.
Sure!..
if(!alreadyExecuted) {
doTrick();
alreadyExecuted = true;
}
Your can use AtomicBoolean
to make sure the task is only called the first time:
import java.util.concurrent.atomic.AtomicBoolean;
public class Once {
private final AtomicBoolean done = new AtomicBoolean();
public void run(Runnable task) {
if (done.get()) return;
if (done.compareAndSet(false, true)) {
task.run();
}
}
}
Usage:
Once once = new Once();
once.run(new Runnable() {
@Override
public void run() {
foo();
}
});
// or java 8
once.run(() -> foo());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With