how can i cancel Future.delayed function calling - dart

how can i cancel Future.delayed
i am using Future.delayed for some task, but if i want to cancel this delayed task, so is their any method or any other things to use.
Future.delayed(Duration(seconds: 10),(){
setState(() {
//some method calling
});
});

what about declare a bool value
bool _executeFuture=true;
then
Future.delayed(Duration(seconds: 10),(){
if(_executeFuture){
setState(() {
//some method calling
});
}
});
Now whenever you want to cancel Future just use
_executeFuture=false;
Also, You can use CancelableOperation from https://pub.dartlang.org/packages/async

Related

Break async / wait declaration chain in Dart

I wonder if you can escape the async / wait chain in Dart. AFAIK every time you want to make a sync call to an async function you must use await but this forces you to make the function which holds the instruction to become async too.
Here is an example:
Future<String> helloAsync() async{
return Future.delayed(const Duration(seconds: 2), ()=>'Hello');
}
void helloSync(){
//call helloAsync synchronously (somehow without making this function async)
//print returned value
}
void main(){
helloSync();
}
In here if I want to make a sync call to helloAsync() inside the HellowSync() I must add await like:
void helloSync(){
String s = await helloAsync();
print(s);
}
but this will not work until I add the async keyword for it - and if I do this means that I have to do it for main() function too.
Is there a way to break this chain of async / await declaration?
(In the initial example this would mean no async declaration for main function)
You could use .then() instead. You can't return the result of a Future from a synchronous function, but since your helloSync() returns void anyway, .then() might be what you are looking for.
void helloSync(){
helloAsync().then((result) => print(result));
}

Dart callback - passing asynchronous message to parent object

I am trying to pass data (bool) from a child class through a callback Function (ondone) provided by the parent class, which will be called in a periodic function with a boolean argument.
import 'dart:async';
class Flow {
MyTimer timer;
bool done = false;
Function ondone;
Flow() {
ondone = (bool b) => done=b;
}
void addtimer(int t) {
timer = MyTimer(t, ondone);
}
}
class MyTimer {
final int time;
int remaining;
Function callback;
Timer _timer;
MyTimer(this.time, this.callback){
remaining = time;
}
void run() {
_timer = Timer.periodic(
Duration(seconds: 1),
(t) {
remaining--;
if (remaining == 0) {
_timer.cancel();
callback(true);
}
});
}
}
But I am unable to figure out if callback is being called or not, because print function (in main) is not printing anything which is wrapped in an if expression.
void main() {
var flow=Flow();
flow.addtimer(5);
flow.timer.run();
if(flow.done) print('Timer Finished..');
print('I need to run while timer is working');
}
Passing data from child to parent in an imperative style is important for me (as a beginner).
The call to flow.timer.run() invokes the Timer which executes asynchronously. Your next line of code tests flow.done immediately, and of course it is not done yet. If you do this:
flow.timer.run();
await Future.delayed(Duration(seconds: 6));
if (flow.done) print('Timer Finished..');
Then your main function will pause for 6 seconds by which time the Timer will be complete.
If you do want to wait for the delay, you could code as follows:
Future<void> run() async {
while (remaining > 0) {
await Future.delayed(Duration(seconds: 1));
remaining = remaining - 1;
}
callback(true);
}
and call it as:
await flow.timer.run();
Edit: If you want to run other code in main and then wait, you can do:
var future = flow.timer?.run();
print('Timer is running...');
await future;
if (flow.done) print('Timer Finished..');

Is there a good way to write "wait for variables to change" in Dart's async method?

I wrote a program in Dartlang that stops processing until the variable foo becomes false as shown below.
It is executable, but continuing to return Future in a while statement is clumsy.
Is there a way to write it clearly?
Future asyncMethod() async {
while (foo) {
await new Future(() {
return null;
});
}
Unity's coroutine can be written in a single line as below, so I'd like to make this much clearer.
yield return new WaitWhile(() => foo);
You are polling the variable at intervals using a timer. There are lots of ways to do that. I'd just go for the completely straight-forward implementation:
Future waitWhile(bool test(), [Duration pollInterval = Duration.zero]) {
var completer = new Completer();
check() {
if (!test()) {
completer.complete();
} else {
new Timer(pollInterval, check);
}
}
check();
return completer.future;
}
With that function, you can then just write
await waitWhile(() => foo);
to wait for foo to become false.
By using Future.doWhile.
Without a polling interval:
await Future.doWhile(() => isPaused);
With a polling interval:
if (isPaused) {
await Future.doWhile(() => Future.delayed(interval).then((_) => isPaused));
}

Dart async/await internals

I'm searching for the source of async/await implementations.
I would like to know how do they truly works in order to hack into future.then() to detect if there is code awaiting for execution or not.
Edit
This is what I'm willing to accomplish:
TrackingCompleter completer = new TrackingCompleter();
TrackingFuture future = completer.future;
print("isAwaited: ${future.isAwaited} (F)");
new Future.delayed(new Duration(milliseconds: 500), () {
future.then((_) {
print("executing sorping");
print("isThenExecuted: ${future.thenExecuted} (F)");
new Future.delayed(new Duration(milliseconds: 500), () {
print("isThenExecuted: ${future.thenExecuted} (T)");
exit(1);
});
});
print("isAwaited: ${future.isAwaited} (T)");
print("isThenExecuted: ${future.thenExecuted} (F)");
completer.complete();
});
As far, that's working. What I'd like to do now is to detect if future.then is called manually in the code or automatically with an await statement.
The async/await implementation is based on futures.
Basically, await creates a function that contains the rest of the current function (the "continuation" of the await expression), and then calls then on the future you await with that function as argument.
There are more details needed to handle errors, but that's basically it.
In your case, if you want to know if future.then is called, I recommend just wrapping that particular future. Example:
import "package:async/async.dart";
class ThenWrapper<T> extends DelegatingFuture<T> {
void Function(S Function(T), S Function(Object, StackTrace)) _callback;
ThenWrapper(Future<T> future, this._callback): super(future);
Future<S> then<S>(S onValue(T), {S onError(error, StackTrace st)}) {
_callback(onValue, onError);
return super.super(onValue, onError);
}
}
...
TrackingFuture future = new ThenWrapper(completer.future, ...);
You can change the callback to do whatever you want.

How do I do the equivalent of setTimeout + clearTimeout in Dart?

I'm porting some JavaScript to Dart. I have code that uses window.setTimeout to run a callback after a period of time. In some situations, that callback gets canceled via window.clearTimeout.
What is the equivalent of this in Dart? I can use new Future.delayed to replace setTimeout, but I can't see a way to cancel this. Nor can I find away to call clearTimeout from Dart.
You can use the Timer class
import 'dart:async';
var timer = Timer(Duration(seconds: 1), () => print('done'));
timer.cancel();
If you want to mimic the JavaScript API:
import 'dart:async';
Timer setTimeout(callback, [int duration = 1000]) {
return Timer(Duration(milliseconds: duration), callback);
}
void clearTimeout(Timer t) {
t.cancel();
}

Resources