2021年1月22日星期五

How can I asynchronously stream loaded objects from a list of futures in Dart

I have a list of objects that can be loaded by calling the function object.load(). This function returns a loaded version of the same object asynchronously. I want call the load() funcion of all objects in a list at the same time and stream the loaded versions as soon as they finish loading. The code below works but the program is loading one object at a time.

Sender:

Stream<ImageIconModel> streamLoadedIcons() async* {      for (var i = 0; i < imageIconModels.length; i++) {        yield await imageIconModels[i].load().then((loadedIconModel) {          return loadedIconModel;        });      }    }  

Receiver:

    await for (var loadedIcon in streamLoadedIcons()) {       final var result = doSomething(loadedIcon);       yield result;      }  

The main problem is: In the sender, if I await each load() call, it will do every step in the loop awaiting the load() to finish. But if I remove the "await", I would be returning a future, not the loaded icon.

https://stackoverflow.com/questions/65851235/how-can-i-asynchronously-stream-loaded-objects-from-a-list-of-futures-in-dart January 23, 2021 at 03:01AM

没有评论:

发表评论