brianegan / dart_redux_epics

Redux.dart middleware for handling actions using Dart Streams
MIT License
141 stars 22 forks source link

How to dispatch multiple actions from an Epic #22

Closed cubissimo closed 5 years ago

cubissimo commented 5 years ago

Is there a pattern to dispatch multiple actions from an Epic?

return Observable(actions)
        .ofType(TypeToken<SearchAction>())
        .debounce(Duration(milliseconds: 300))
        .switchMap((SearchAction action) {
      return _getResults(store, action)
          .map((result) => OnSearchResult(result))
        //want to dispatch a analytics action here something like
        // .map((result) => [OnSearchResult(result), SearchAnalyticAction(result)])
          .takeUntil(actions.where((action) => action is CancelSearchAction));

is there a way to do that? Or is better to have 2 separeted epics listen same action (SearchAction)?

tks

brianegan commented 5 years ago

Hey there -- Yep, you have total control of what's emitted from the Stream! In this case, you're only emitting one thing from this stream: A list of actions.

Instead, you need to emit two items! You have a few ways to do that, but the easiest for this case will be using the expand operator. It's kinda like map, but allows you to emit multiple items: https://docs.flutter.io/flutter/dart-async/Stream/expand.html

The example becomes:

return Observable(actions)
        .ofType(TypeToken<SearchAction>())
        .debounce(Duration(milliseconds: 300))
        .switchMap((SearchAction action) {
      return _getResults(store, action)
          .expand((result) => [OnSearchResult(result), SearchAnalyticAction(result)])
          .takeUntil(actions.where((action) => action is CancelSearchAction));
cubissimo commented 5 years ago

Superb! Thanks @brianegan