aidanmack
aidanmack

Reputation: 558

combine FutureProviders into a StateNotifierProvider

I'm using riverpod with Freezed unions.

I'm trying to merge/watch two FutureProviders that both return the same type into a StateNotifierProvider and use them to set state.

I've noticed that because I'm watching two futureProviders, that it creates two instances of the StateNotifierProvider because...

From Logging I can see that init method gets called twice, clocking state gets called twice and DPS state gets called once.

I'm failing at the first hurdle but my hope is to:

I realise the below example has no timer implemented, but I need to figure out the problem with StateNotfierProvider, and then I'll move on to adding the pause etc.

To be honest im not even sure this is the correct way of doing things?

I thought about maybe setting up two consumers for each futureprovider in the widget but this seems a little cumbersome. Would be good if I could manage multiple future providers in a state provider.

final clockingState = StateNotifierProvider<ClockingNotifier, ClockingState>(
    (ref) => ClockingNotifier(
        ref.watch(loadingItineraryProvider), ref.watch(clockingDps)));

class ClockingNotifier extends StateNotifier<ClockingState> {
  final AsyncValue<ClockingState> itineraryState;
  final AsyncValue<ClockingState> clockingDps;

  ClockingNotifier(this.itineraryState, this.clockingDps)
      : super(ClockingState.init()) {
    init();
  }

  void init() {
    logger.d("the init method");
    itineraryState.whenData((ClockingState clockingState) {
      logger.d("clocking state");
      state = clockingState;
    });
    clockingDps.whenData((ClockingState dps) {
      logger.d("DPS state");
      state = dps;
    });
  }
}

Upvotes: 9

Views: 1096

Answers (1)

Michel
Michel

Reputation: 247

If you need the FutureProviders just for the ClockingNotifier, you should think about moving them completely inside the ClockingNotifier (call the Futures inside the init() Method or add functions inside ClockingNotifier to load the futures and update the state of the Notifier directly afterwards).

This gives you more control and a better Notifier flow.

Upvotes: 0

Related Questions