Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue of Future in dart

I want to implement a chat system.

I am stuck at the point where user sends multiple messgaes really fast. Although all the messages are reached to the server but in any order.

So I thought of implementing a queue where each message shall

  1. First be placed in queue

  2. Wait for its turn

  3. Make the post request on its turn

  4. Wait for around 5 secs for the response from server

  5. If the response arrives within time frame and the status is OK, message sent else message sending failed.

  6. In any case of point 5, the message shall be dequeued and next message shall be given chance.

Now, the major problem is, there could be multiple queues for each chat head or the user we are talking to. How will I implement this? I am really new to dart and flutter. Please help. Thanks!

like image 833
dealoell Avatar asked Oct 05 '18 18:10

dealoell


People also ask

How do you use the future in darts?

A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Note: Uncompleted is a Dart term referring to the state of a future before it has produced a value.

What is queue in Dart?

A Queue is a collection that can be manipulated at both ends. Queues are useful when you want to build a first-in, first-out collection. Simply put, a queue inserts data from one end and deletes from another end.

Is Dart synchronous or asynchronous?

Dart uses Future objects to represent asynchronous operations.

How is Whencompleted () different from then () in Future?

. whenComplete will fire a function either when the Future completes with an error or not, instead . then will fire a function after the Future completes without an error. This is the asynchronous equivalent of a "finally" block.


1 Answers

It sounds like you are describing a Stream - a series of asynchronous events which are ordered.

https://www.dartlang.org/guides/language/language-tour#handling-streams https://www.dartlang.org/guides/libraries/library-tour#stream

Create a StreamController, and add messages to it as they come in:

var controller = StreamController<String>();
// whenever you have a message
controller.add(message);

Listen on that stream and upload the messages:

await for(var messsage in controller.messages) {
  await uploadMessage(message);
}
like image 166
Nate Bosch Avatar answered Nov 15 '22 11:11

Nate Bosch