How can Bloc listen to stream and emit state

1,755

Solution 1

You should use emit in eventHandler, use below code to complete your task:

abstract class Event {}

class DemoEvent extends Event {}

var fakeStream =
    Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15);

class DemoBloc extends Bloc<Event, int> {
  DemoBloc() : super(0) {
    fakeStream.listen((_) {
      // add your event here
      add(DemoEvent());
    });
    on<DemoEvent>((_, emit) {
      // emit new state
      emit(state + 1);
    });
  }
}

Solution 2

you sould use emit.forEach( )
where forEach must return a state which will be emitted

like this

on<DemoEvent>((event, emit) async{
  await emit.forEach(
  investmentClubRepository.onNewMessage(),
  onData: (message){
  return yourState;
   });
});
Share:
1,755
Vingtoft
Author by

Vingtoft

Updated on November 23, 2022

Comments

  • Vingtoft
    Vingtoft over 1 year

    In my flutter app, I use flutter_bloc for state management.

    The bloc in question uses a repository. The repository subscribes to a websocket, and new data is added to a stream.

    Problem: My bloc listens to the stream:

    InvestmentClubBloc({
        required this.investmentClubRepository
      }) : super(InvestmentClubLoading()) {
        onChangeSubscription = investmentClubRepository.onNewMessage.listen(
          (event) {
            emit(NewMessageState(event); // <-- The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test
          },
        );
      }
    

    The problem is that emit does not work (I get the warning "The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test")

    How can bloc listen to a stream and emit new states depending on stream events?

    • 聂超群
      聂超群 over 2 years
      Which flutter_bloc version do you use?
    • Vingtoft
      Vingtoft over 2 years
      flutter_bloc: ^8.0.0
    • 聂超群
      聂超群 over 2 years
      Please check my answer below.
    • Shady Mohamed Sherif
      Shady Mohamed Sherif over 2 years
      Thank you for the nice question
  • Vingtoft
    Vingtoft over 2 years
    To clarify: Even though we listen on the stream in the bloc, the bloc should add events to itself? I do recognise this solution would work, but it seems like a lot of overhead code.
  • 聂超群
    聂超群 over 2 years
    The code is based on your use case. If you have a stream, maybe a StreamBuilder can fulfill your requirement though, you don't need bloc then.
  • Marcel Dz
    Marcel Dz almost 2 years
    hey, maybe you could help me out here? stackoverflow.com/questions/72716031/…
  • Marcel Dz
    Marcel Dz almost 2 years
    hey maybe you could help me out here? stackoverflow.com/questions/72716031/…