[英]Flutter: How to Queue multiple streams
I have stream like the below-mentioned code, here want to merge streams and wanted to call it one by one whenever it required.我有 stream 就像下面提到的代码,这里想合并流并想在需要时一一调用。
main() {
Stream<String> stream = new Stream.fromFuture(getData());
stream.listen((data) {
print("DataReceived: "+data);
}, onDone: () {
print("Task Done");
});
}
Future<String> getData() async {
await Future.delayed(Duration(seconds: 5)); //Mock delay
print("Fetched Data");
return "This a test data";
}
onDone
will be called after 5 seconds. onDone
将在 5 秒后调用。
For it, StreamQueue
can be used to combine multiple streams对于它,可以使用
StreamQueue
组合多个流
Add Dependency:添加依赖:
async: ^2.4.1
Use StreamQueue:使用流队列:
void main() async {
Stream<String> stream1 = new Stream.fromFuture(getData(2));
Stream<String> stream2 = new Stream.fromFuture(getData(4));
Stream<String> stream3 = new Stream.fromFuture(getData(6));
var streams = StreamGroup.merge([stream1, stream2, stream3]);
var data = StreamQueue(streams);
var first = await data.next;
print(first);
var second = await data.next;
print(second);
var third = await data.next;
print(third);
var third1 = await data.next;
print(third1);
}
Future<String> getData(int duration) async {
await Future.delayed(Duration(seconds: duration)); //Mock delay
return "This a test data for duration $duration";
}
Output: Output:
I/flutter ( 7950): This a test data for duration 2
I/flutter ( 7950): This a test data for duration 4
I/flutter ( 7950): This a test data for duration 6
data.next
will provide you the first stream in Queue which is in our case is stream1, here we can take the future value and use.data.next
将为您提供队列中的第一个 stream,在我们的例子中是 stream1,这里我们可以取未来值并使用。stream.next
gives next stream in the queue if nothing exists in queue & stream.next is performed then it will throw an exception.如果队列中不存在任何内容,
stream.next
在队列中给出下一个 stream 并且执行 stream.next 然后它将抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.