1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Flutter Bloc Problem with timeout on stream listening

Discussão em 'Mobile' iniciado por Stack, Setembro 27, 2024 às 15:02.

  1. Stack

    Stack Membro Participativo

    I'm using Bloc library in my Flutter application.

    On processing some event I'm listening stream and want to handle timeout.

    This is code example:

    await emit.onEach(
    bluetoothConnection.input!,
    onData: (data) {
    answer = answer + String.fromCharCodes(data);
    if (answer.contains('hello:eek:k')) {
    isAnswered = true;
    emit(
    ConnectionSuccessState(
    device: event.device.copyWith(
    isConnected: true,
    bluetoothConnection: bluetoothConnection,
    ),
    ),
    );
    }
    },
    ).timeout(const Duration(seconds: 1), onTimeout: () {
    debugPrint('onTimeout');
    });


    When timeout occur I see debug record

    I/flutter ( 5875): onTimeout


    And then I got exception like this

    E/flutter ( 5875): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 'package:bloc/src/emitter.dart': Failed assertion: line 150 pos 7: '_disposables.isEmpty':
    E/flutter ( 5875):
    E/flutter ( 5875): An event handler completed but left pending subscriptions behind.
    E/flutter ( 5875): This is most likely due to an unawaited emit.forEach or emit.onEach.
    E/flutter ( 5875): Please make sure to await all asynchronous operations within event handlers.
    E/flutter ( 5875):
    E/flutter ( 5875): **BAD**
    E/flutter ( 5875): on<Event>((event, emit) {
    E/flutter ( 5875): emit.forEach(...);
    E/flutter ( 5875): });
    E/flutter ( 5875):
    E/flutter ( 5875): **GOOD**
    E/flutter ( 5875): on<Event>((event, emit) async {
    E/flutter ( 5875): await emit.forEach(...);
    E/flutter ( 5875): });


    What the right way to process timeout in my stream listening?

    Continue reading...

Compartilhe esta Página