Hello everyone
I have one class 'Example' who needs to do some computation. I call start() which call _next(). During the computation _next() calls itself couple of time but in my example I simulate that with a Timer. here is my code
import "dart:async";
main() {
Example ex = new Example();
for (var i = 0 ; i < 3 ; i++) {
ex.start().then((nbr) {
print(nbr);
});
}
}
class Example {
/// for _next
Completer _insideCompleter;
/// from start() to outside
Completer _outsideCompleter;
Example();
/// start is just a better public api than next when we start the exercise
Future<int> start() {
_insideCompleter = new Completer();
_outsideCompleter = new Completer();
_next().then((int value) {
print("value: $value");
_outsideCompleter.complete(value);
}).catchError((message) {
print("information: $message");
});
return _outsideCompleter.future;
}
/// _next handle the flow with the status
Future<int> _next() {
new Timer(new Duration(seconds: 6), () {
_insideCompleter.complete(15);
});
return _insideCompleter.future;
}
}
it finishes with : Bad state: Future already completed. but as you can see in the start(). the Completer are re-created with new. So I don't understand why it is already complete.
If anybody can explain why it's not correct to code like that and maybe give me some interesting links it would be great
Cheers!
I'm not entirely sure what your intention with the code is but I think you should either
Example ex = new Example();
for (var i = 0 ; i < 3 ; i++) { // create a new Example() for each iteration here
ex.start().then((nbr) { // or ensure that the next iteration is not executed
print(nbr); // before the previous is completed.
});
}
with this code ex.start() is called 3 times before the first call is completed.
Here the main issue is about completers called in the callback function
_next().then((int value) {
print("value: $value");
_outsideCompleter.complete(value); // this line
})
and
new Timer(new Duration(seconds: 6), () {
_insideCompleter.complete(15); // this line
});
Because this 2 function are called after your loop and your completer are attribute, all the callback will use the latest _outsideCompleter and _insideCompleter created.
So after than one of the callback have "consume" your completer, the others will create exception of 'Bad state: Future already completed'
here a version that works
import "dart:async";
main() {
Example ex = new Example();
for (var i = 0 ; i < 3 ; i++) {
ex.start().then((nbr) {
print(nbr);
});
}
}
class Example {
Example();
/// start is just a better public api than next when we start the exercise
Future<int> start() {
var outsideCompleter = new Completer(); // create localy each times
_next().then((int value) {
print("value: $value");
outsideCompleter.complete(value);
}).catchError((message) {
print("information: $message");
});
return outsideCompleter.future;
}
/// _next handle the flow with the status
Future<int> _next() {
var insideCompleter = new Completer(); // create localy each times
new Timer(new Duration(seconds: 6), () {
insideCompleter.complete(15);
});
return insideCompleter.future;
}
}
Related
I'm currently migrating an App's logic code from C# to Dart and I'm looking for a similiar collection type in Dart to C#s BlockingCollection. I basically want a queue where i can iterate infinitely. If the queue is empty it just waits until a new element is added.
Is that possible in Dart?
Best
You can use a StreamController.
Here I translated the first C# example for BlockingCollection
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
class BlockingCollectionDemo
{
static async Task Main()
{
await AddTakeDemo.BC_AddTakeCompleteAdding();
}
}
class AddTakeDemo
{
// Demonstrates:
// BlockingCollection<T>.Add()
// BlockingCollection<T>.Take()
// BlockingCollection<T>.CompleteAdding()
public static async Task BC_AddTakeCompleteAdding()
{
using (BlockingCollection<int> bc = new BlockingCollection<int>())
{
// Spin up a Task to populate the BlockingCollection
Task t1 = Task.Run(() =>
{
bc.Add(1);
bc.Add(2);
bc.Add(3);
bc.CompleteAdding();
});
// Spin up a Task to consume the BlockingCollection
Task t2 = Task.Run(() =>
{
try
{
// Consume consume the BlockingCollection
while (true) Console.WriteLine(bc.Take());
}
catch (InvalidOperationException)
{
// An InvalidOperationException means that Take() was called on a completed collection
Console.WriteLine("That's All!");
}
});
await Task.WhenAll(t1, t2);
}
}
}
to dart using a StreamController instead of BlockingCollection, and Future instead of Task.
import 'dart:async';
Future<void> main() async {
await addTakeCompleteAdding();
}
// Demonstrates:
// StreamController<T>.add()
// StreamController<T>.stream
// StreamController<T>.close()
Future<void> addTakeCompleteAdding() async {
StreamController<int> bc = StreamController<int>();
// Spin up a Future to populate the StreamController
Future<void> t1 = Future(() {
bc.add(1);
bc.add(2);
bc.add(3);
bc.close();
});
// Spin up a Future to consume the StreamController
Future<void> t2 = Future(() async {
// Consume consume the StreamController
await for (final element in bc.stream) {
print(element);
}
// Exits the loop when the stream is completed/closed
print("That's All!");
});
await Future.wait([t1, t2]);
}
That said, the StreamController differs a bit from BlockingCollection in that it is not a queue. A Stream in dart by default, can only have one subscription, unless you create a broadcast stream. Stream is more like an async enumerable in C#.
If you really need a queue data structure you can use the async package, which has a StreamQueue class that you can use to wrap the stream from the StreamController.
Here is the above code modified to use a StreamQueue:
import 'dart:async';
import 'package:async/async.dart';
Future<void> main() async {
await addTakeCompleteAdding();
}
// Demonstrates:
// StreamController<T>.add()
// StreamController<T>.stream
// StreamController<T>.close()
// StreamQueue<T>.next
Future<void> addTakeCompleteAdding() async {
StreamController<int> bc = StreamController<int>();
StreamQueue<int> queue = StreamQueue<int>(bc.stream);
// Spin up a Future to populate the StreamController
Future<void> t1 = Future(() {
bc.add(1);
bc.add(2);
bc.add(3);
bc.close();
});
// Spin up a Future to consume the StreamQueue
Future<void> t2 = Future(() async {
try {
while (true) {
// Consume consume the StreamQueue
print(await queue.next);
}
} on StateError catch (e) {
// A StateError means that next was called on a completed collection
print("That's all!");
}
});
await Future.wait([t1, t2]);
}
You can also write your own queue, based on futures instead of a stream:
import "dart:async" show Completer;
import "dart:collection" show Queue;
abstract class BlockingQueue<T> {
factory BlockingQueue() = _BlockingQueue;
Future<T> removeNext();
void add(T value);
}
class _BlockingQueue<T> implements BlockingQueue<T> {
final Queue<T> _writes = Queue();
final Queue<Completer<T>> _reads = Queue();
Future<T> removeNext() {
if (_writes.isNotEmpty) return Future.value(_writes.removeFirst());
var completer = Completer<T>();
_reads.add(completer);
return completer.future;
}
void add(T value) {
if (_reads.isNotEmpty) {
_reads.removeFirst().complete(value);
} else {
_writes.add(value);
}
}
}
You can also consider a double-blocking queue, where the add method also "blocks" if there is no-one to accept the value yet. It's not even that hard,.
import "dart:async" show Completer;
import "dart:collection" show Queue;
abstract class BlockingQueue<T> {
factory BlockingQueue() = _BlockingQueue;
Future<T> removeNext();
Future<void> add(T value);
}
class _BlockingQueue<T> implements BlockingQueue<T> {
final Queue<T> _writes = Queue();
final Queue<Completer<T>> _completers = Queue();
Future<T> removeNext() {
if (_writes.isNotEmpty) {
assert(_completers.isNotEmpty);
var completer = _completers.removeFirst();
completer.complete(_writes.removeFirst());
return completer.future;
}
var completer = Completer<T>();
_completers.add(completer);
return completer.future;
}
Future<void> add(T value) {
if (_writes.isEmpty && _completers.isNotEmpty) {
var completer = _completers.removeFirst();
completer.complete(value);
return completer.future;
}
var completer = Completer<T>();
_completers.add(completer);
_writes.add(value);
return completer.future;
}
}
That said, if you want to use a for (... in ...)-like loop, you probably do want to go with a Stream and use await for (... in theStream).
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..');
I am searching for something like the following, where I return an object from a method, which can be awaited, and completed from its origin function:
Future<dynamic> customFunction() {
// The following class does not exist, but I am searching for a class that would fill that gap.
FutureWithCompletion future = FutureWithCompletion();
() async { // A callback that represents the usecase.
// some computation
future.completeWith('something');
}
return future;
}
/// This function accesses [customFunction].
/// It should print out "something" once the computation is done.
anotherFunction() async => print(await customFunction());
You need to use a Completer:
Future<String> method() {
final completer = Completer<String>();
Timer(Duration(seconds: 5), () => completer.complete('result'));
return completer.future;
}
return Future.value('something`);
otherwise use a Completer https://api.dartlang.org/stable/2.0.0/dart-async/Completer-class.html
In Python there is a function called Time.Sleep () to pause the execution of a period of time, some alternative in Vala.
What I try to do is execute a While (True) but the content is executed in a certain period of time, for example 5 seconds.
Maybe have a look at the async example here:
// Build with: valac --pkg=gio-2.0 example.vala
public async void nap (uint interval, int priority = GLib.Priority.DEFAULT) {
GLib.Timeout.add (interval, () => {
nap.callback ();
return false;
}, priority);
yield;
}
private async void do_stuff () {
yield nap (1000);
}
private static int main (string[] args) {
GLib.MainLoop loop = new GLib.MainLoop ();
do_stuff.begin ((obj, async_res) => {
loop.quit ();
});
loop.run ();
return 0;
}
https://wiki.gnome.org/Projects/Vala/AsyncSamples
I'm trying to create a server-side Dart class that performs various data-related tasks. All of these tasks rely on the database having been first initialized. The problem is that the init of the database happens asynchronously (returns a Future). I first tried to put the init code into the constructor, but have given up on this approach as it seems to not be viable.
I am now attempting to figure out how to force the DB initialization as a first step in any method call that accesses data. So in other words, when attemptLogin() is called below, I'd like to first check if the DB has been initialized and initialize it if necessary.
However, there are two obstacles. If the database hasn't been initialized, the code is straightforward - initialize the db, then use the then() method of the returned future to do the rest of the function. If the db is not yet initialized, what do I attach my then() method to?
Second related question is what happens when a database is currently being initialized but this process is not yet complete? How can I pull in and return this "in-progress" Future?
This is the basic gist of the code I'm trying to wrangle:
class DataManager {
bool DbIsReady = false;
bool InitializingDb = false;
Db _db;
Future InitMongoDB() {
print("Initializing MongoDB");
InitializingDb = true;
_db = new Db("mongodb://127.0.0.1/test");
return _db.open().then((_) {
DbIsReady = true;
InitializingDb = false;
});
}
Future<List> attemptLogin(String username, String password) {
Future firstStep;
if ((!DbIsReady) && (!InitializingDb) {
Future firstStep = InitMongoDB()
}
else if (InitializingDb) {
// Need to return the InitMongoDB() Future that's currently running, but how?
}
else {
// How do I create a blank firstStep here?
}
return firstStep.then((_) {
users = _db.collection("users");
return // ... rest of code cut out for clarity
});
}
}
Thanks in advance for your help,
Greg
Just return
return new Future<bool>.value(true);
// or any other value instead of `true` you want to return.
// or none
// return new Future.value();
Just keep the future alive:
class DataManager {
Future _initializedDb;
Future initMongoDb() { ... }
Future<List> attemptLogin(String username, String password) {
if (_initializedDb == null) {
_initializedDb = initMongoDB();
}
return _initializedDb.then((db) {
users = db.collection("users");
return // ... rest of code cut out for clarity
});
}
}
You might need to pay attention for the error-case. It's up to you if you want to deal with errors in the initMongoDB or after it.
One of the possible solutions:
import "dart:async";
void main() {
var dm = new DataManager();
var selectOne = dm.execute("SELECT 1");
var selectUsers = dm.execute("SELECT * FROM users");
var users = selectOne.then((result) {
print(result);
return selectUsers.then((result) {
print(result);
});
});
users.then((result) {
print("Goodbye");
});
}
class Event {
List<Function> _actions = new List<Function>();
bool _raised = false;
void add(Function action) {
if (_raised) {
action();
} else {
_actions.add(action);
}
}
void raise() {
_raised = true;
_notify();
}
void _notify() {
if (_actions.isEmpty) {
return;
}
var actions = _actions.toList();
_actions.clear();
for (var action in actions) {
action();
}
}
}
class DataManager {
static const int _STATE_NOT_INITIALIZED = 1;
static const int _STATE_INITIALIZING = 2;
static const int _STATE_READY = 3;
Event _initEvent = new Event();
int _state = _STATE_NOT_INITIALIZED;
Future _init() {
if (_state == _STATE_NOT_INITIALIZED) {
_state = _STATE_INITIALIZING;
print("Initializing...");
return new Future(() {
print("Initialized");
_state = _STATE_READY;
_initEvent.raise();
});
} else if (_state == _STATE_INITIALIZING) {
print("Waiting until initialized");
var completer = new Completer();
_initEvent.add(() => completer.complete());
return completer.future;
}
return new Future.value();
}
Future execute(String query, [Map arguments]) {
return _init().then((result) {
return _execute(query, arguments);
});
}
Future _execute(String query, Map arguments) {
return new Future.value("query: $query");
}
}
Output:
Initializing...
Waiting until initialized
Initialized
query: SELECT 1
query: SELECT * FROM users
Goodbye
I think that exist better solution but this just an attempt to answer on your question (if I correctly understand you).
P.S. EDITED at 11 July 2014
Slightly modified (with error handling) example.
import "dart:async";
void main() {
var dm = new DataManager();
var selectOne = dm.execute("SELECT 1");
var selectUsers = dm.execute("SELECT * FROM users");
var users = selectOne.then((result) {
print(result);
return selectUsers.then((result) {
print(result);
});
});
users.then((result) {
print("Goodbye");
});
}
class DataManager {
static const int _STATE_NOT_INITIALIZED = 1;
static const int _STATE_INITIALIZING = 2;
static const int _STATE_READY = 3;
static const int _STATE_FAILURE = 4;
Completer _initEvent = new Completer();
int _state = _STATE_NOT_INITIALIZED;
Future _ensureInitialized() {
switch (_state) {
case _STATE_NOT_INITIALIZED:
_state = _STATE_INITIALIZING;
print("Initializing...");
new Future(() {
print("Initialized");
_state = _STATE_READY;
// throw null;
_initEvent.complete();
}).catchError((e, s) {
print("Failure");
_initEvent.completeError(e, s);
});
break;
case _STATE_INITIALIZING:
print("Waiting until initialized");
break;
case _STATE_FAILURE:
print("Failure detected");
break;
default:
print("Aleady intialized");
break;
}
return _initEvent.future;
}
Future execute(String query, [Map arguments]) {
return _ensureInitialized().then((result) {
return _execute(query, arguments);
});
}
Future _execute(String query, Map arguments) {
return new Future.value("query: $query");
}
}
For those that are still wondering how to create a blank Future in Dart and later complete them, you should use the Completer class like in the next example.
class AsyncOperation {
final Completer _completer = new Completer();
Future<T> doOperation() {
_startOperation();
return _completer.future; // Send future object back to client.
}
// Something calls this when the value is ready.
void finishOperation(T result) {
_completer.complete(result);
}
// If something goes wrong, call this.
void _errorHappened(error) {
_completer.completeError(error);
}
}
Future<Type> is non nullable in Dart, meaning that you have to initialize it to a value. If you don't, Dart throws the following error:
Error: Field should be initialized because its type 'Future<Type>' doesn't allow null.
To initialize a Future<Type>, see the following example:
Future<String> myFutureString = Future(() => "Future String");
Here "Future String" is a String and so the code above returns an instance of Future<String>.
So coming to the question of how to create a blank/empty Future, I used the following code for initializing an empty Future List.
Future<List> myFutureList = Future(() => []);
I found this link to be quite useful in understanding Futures in Flutter and Dart: https://meysam-mahfouzi.medium.com/understanding-future-in-dart-3c3eea5a22fb