RedBrogdon / rebloc

A state management library for Flutter that combines aspects of Redux and BLoC.
BSD 3-Clause "New" or "Revised" License
215 stars 21 forks source link

Dispatch an action from the context of extended SimpleBloc #12

Closed mbn18 closed 5 years ago

mbn18 commented 5 years ago

Hi,

In my bloc class I listen to location event. How can I dispatch an action on each event?

class TrackingBloc extends SimpleBloc<AppState> {
    ...
    bg.BackgroundGeolocation.onLocation((bg.Location location) {
        dispatcher(DoSomethinWithLocation(location));
    }
    ...
}
RedBrogdon commented 5 years ago

Thanks for asking. There are a couple ways you can do it, depending on whether you prefer SimpleBloc or Bloc

If you're using SimpleBloc (and it looks like you are), you can define some Actions that look like this:

When your SimpleBloc's middleware receives a BeginMonitoringLocation action, it can store the dispatcher it gets in middleware and use it later to dispatch LocationUpdated actions with the new location information whenever onLocation fires.

If you're using Bloc, you can do something similar with the same actions. Instead of using the dispatcher method, you'd just use asyncExpand to add new LocationUpdated actions directly to the stream. I rarely have a need for asyncExpand, but I always feel fancy using it. 😄

mbn18 commented 5 years ago

Thanks Andrew, seems to work as expected. If any one interested, here is the implementation:

class TrackingBloc extends SimpleBloc<AppState> {

  @override
  Action middleware(dispatcher, state, action) {
    ...
    if (action is StartLocationListenersAction) {
      LocationListener(dispatcher);
      return action;
    }
    return action;
  }

  AppState reducer(state, action) {
    ...
    return state;
  }
}

class LocationListener {
  LocationListener(DispatchFunction dispatcher) {
    bg.BackgroundGeolocation.onLocation((bg.Location location) {
      dispatcher(LocationUpdatedAction(location));
    });
  }
}