Queue of Future in dart
Asked Answered
W

1

6

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!

Wie answered 5/10, 2018 at 18:38 Comment(0)
M
13

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);
}
Maigre answered 8/10, 2018 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.