Queue of Future in dart

╄→гoц情女王★ 提交于 2020-05-12 05:05:27

问题


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!


回答1:


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);
}


来源:https://stackoverflow.com/questions/52671529/queue-of-future-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!