How to achieve concurrency in Dart stream controller

74 Views Asked by At

Suppose I have an StreamController and I want to use this controller to add event to process multiple request at one (parallel) from app.

What I implemented was presented below:

In main.dart

    final controller = StreamController<Req>.broadcast();

    final resStream = controller.stream.asyncMap<Res>((request) {
      switch (request.method) {
        case "get":
          return  Future.delayed(
            const Duration(seconds: 10),
            () => const Res('response after 10s'),
          );
        case "post":
        default:
          return  Future.delayed(
            const Duration(seconds: 5),
            () => const Res('response after 5s'),
          );
      }
    });

    resStream.listen((event) {
      print('+++ response from stream: ${event.value}');
    });

    controller.add(const Req('get'));
    controller.add(const Req('post'));

Class req.dart & res.dart

class Req {
  const Req(this.method);

  final String method;
}

class Res {
  const Res(this.value);

  final String value;
}

After I ran that code. I realize the order of output is same with what order I added into StreamController before.

+++ response from stream: response after 10s
+++ response from stream: response after 5s

In my thinking the output of Req('post') must appear first then to another like this:

+++ response from stream: response after 5s
+++ response from stream: response after 10s

Anyone can help me to clear in this situation. Many thanks!

0

There are 0 best solutions below