【问题标题】:Flutter RxDart switchMap bugFlutter RxDart switchMap bug
【发布时间】:2022-11-09 13:07:47
【问题描述】:

I have a strange bug with Flutter async functions and RxDart (switchMap), here my code:

void main() async {
  Stream periodic = getPeriodicStream();
  Stream mix = periodic.switchMap((parent) {
    return Stream.periodic(const Duration(seconds: 1), (count) {
      return "Result: $parent-$count";
    });
  });
  print(await mix.first);
}

Stream getPeriodicStream() async* {
  Stream periodic = Stream.periodic(const Duration(seconds: 10), (count) {
    print("Periodic stream: $count");
    return "$count";
  });
  //THIS WORK CORRECTLY
  yield* periodic;
  //THIS DOESN'T WORK CORRECTLY
  await for (final period in periodic) {
    yield period;
  }
}

With "yield* periodic;" it works correctly, in the log i see:

flutter: Periodic stream: 0
flutter: Result: 0-0

with "await for (final period in periodic)" that should be the same thing, it doesn't work correctly: it wait for the second stream to return the first stream, log:

flutter: Periodic stream: 0
flutter: Periodic stream: 1
flutter: Result: 0-0

why this strange behavior?

Dartpad: https://dartpad.dev/?id=cc2d1677ad4b05544d10775aaab1fd26

Thanks

    标签: flutter dart asynchronous rxdart


    【解决方案1】:

    I think if you use the below code it will work

    import 'dart:async';
    
    Future<void> main() async {
      Stream periodic = getPeriodicStream();
      Stream mix = periodic.switchMap((parent) {
    return Stream.periodic(const Duration(seconds: 1), (count) {
      return "Result: $parent-$count";
    });
      });
      print(await mix.first);
    }
    
    Future<Stream<String>> getPeriodicStream() async* {
      Stream periodic = Stream.periodic(const Duration(seconds: 10), (count) {
    print("Periodic stream: $count");
    return "$count";
      });
      //THIS WORK CORRECTLY
      yield* periodic;
      //THIS DOESN'T WORK CORRECTLY
      await for (final period in periodic) {
        yield period;
      }
    }
    
      猜你喜欢
      • 2018-11-28
      • 2019-07-19
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2020-01-26
      • 2021-02-19
      相关资源
      最近更新 更多