mardi 26 novembre 2019

Best practice to use mapEventToState with incoming streams?

Is there any elegant way to map incoming streams from a private api directly inside mapEventToState() without having to create redundant private events in the bloc?

I came with this solution. It's ok with one single stream, but with multiple streams it starts to get a mess. Thanks in advance.

// (don't mind the imports, this is the bloc file)

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {


  final MyPrivateApi api = MyPrivateApi.instance; // singleton

  ExampleBloc() {
    // api has a stream of booleans
    api.myStream.listen((b) {
    // if it's true fire this event
    if (b) this.add(_MyPrivateEvent());
  }

  @override
  ExampleState get initialState => InitialExampleState();

  @override
  Stream<ExampleState> mapEventToState(
    ExampleEvent event,
  ) async* {
    if (event is _MyPrivateEvent) {
      yield SomeState;
    }
  }



// private Event
class _MyPrivateEvent extends ExampleEvent {

}

Aucun commentaire:

Enregistrer un commentaire