brianegan / flutter_redux

A library that connects Widgets to a Redux Store
MIT License
1.65k stars 219 forks source link

is it possible to acces a store variable via selectors without building a widget? #213

Closed Gab0rB closed 3 years ago

Gab0rB commented 3 years ago

Hi there,

i'm playing around with the redux store for a few weeks now. Nice work btw!

Now I'm facing the following issue: when i try to select a store variable outside of the widget tree in some function, the only way i found was like this:

StoreProvider.of<AppState>(context).onChange.listen((state) { // do something here with state.variable });

In Angular i know there are selectors, where i can listen to a specific value. Here i would get the state on every state change, also if my value stays the same.

Is there a way to do this or do i have to go always over the whole state?

brianegan commented 3 years ago

store.onChange is a Stream<AppState>, which means it can be transformed like so:

final Stream<SubState> substateStream = StoreProvider.of<AppState>(context).onChange
  .map((AppState appstate) => appstate.substate) // select some substate
  .distinct(); // If the same SubState is emitted twice in a row, ignore it.

final StreamSubscription<SubState> substateSubscription = substateStream.listen((SubState substate) => print(substate));

substateSubscription.cancel(); // Sometime in the Future when you want to stop listening to the substate stream, maybe when a Widget is disposed.
Gab0rB commented 3 years ago

thanks a lot!