Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subscribe to stream in middleware #90

Closed
ronmany opened this issue Oct 17, 2018 · 1 comment
Closed

Subscribe to stream in middleware #90

ronmany opened this issue Oct 17, 2018 · 1 comment

Comments

@ronmany
Copy link

ronmany commented Oct 17, 2018

I have a middleware that needs to response to event from the hardware.
this HW events needs to fire different actions that changes the redux state.
I already have a stream setup. How would I subscribe to this stream in the middleware?

Thank you

@brianegan
Copy link
Owner

brianegan commented Oct 31, 2018

Hey there -- sorry for the delay. Very busy work/travel times.

For this case, I'd recommend checking out the redux_epics package. It will provide a nice way to merge Streams with Middleware.

In your case, you could either supply the Stream to your Middleware / Epic function via the constructor, or dispatch an action that contains the Stream.

Using a constructor would look something like this:

class MyStreamMiddleware extends MiddlewareClass<AppState> {
    final Stream<String> myStream;
    StreamSubscription<String> _subscription;

    MyStreamMiddleware(this.myStream);

   @override
    void call(Store<AppState> store, dynamic action, NextDispatcher next) {
      if (action is ListenToStreamAction) {
        _subscription = stream.listen((data) {
          store.dispatch(DataReceivedAction(data));
        })
      } else if (action is StopListeningAction) {
        _subscription?.cancel();
      }

      next(action);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants