How to listen for values of a StreamProvider in another Provider and not get duplicates

1,313

Your providers are fine. However, docChanges returns an array of documents changed since the previous snapshot, and if it's the first snapshot, will contain all documents.

You are using the autoDispose modifier on your providers. So, if the widget (or other provider, etc.) you are reading your providers from is disposed, your providers will be as well. This would lead to a fresh read from your database, leading to all documents being returned by docChanges.

Try removing the autoDispose modifier and see what happens.

Share:
1,313
chessasuke
Author by

chessasuke

Updated on December 28, 2022

Comments

  • chessasuke
    chessasuke over 1 year

    I want to listen to a firebase collection in real-time using StreamProvider from Riverpod and read the values into another Provider but nothing I have tried works.

    /// StreamProvider
    final firstProvider = StreamProvider.autoDispose((ref) async* {
      final stream = FirebaseFirestore.instance
          .collection('someCollection')
          .orderBy('timestamp', descending: true)
          .snapshots()
          .distinct();
    
      await for (final value in stream) {
        print('value: $value');
        yield value;
      }
    }
    
    final secondProvider = FutureProvider.autoDispose((ref) async {
      final first_provider = await ref.watch(firstProvider);
      print(first_provider .whenData((value) => value.docChanges.length));
      ...
    });
    

    I thought that by using docChanges I would only get new data, but instead, it duplicates on each rebuild.

    Any ideas as to what I am doing wrong?

  • chessasuke
    chessasuke about 3 years
    Hi, thanks for your answer! Yes, I had actually done it already and solved the problem, though I don't think is the right approach. With the .autodispose modifier we have a new property which is ref.mantainstate, which is false by default. According to the docs riverpod.dev/docs/concepts/modifiers/auto_dispose by setting this to true we wont trigger any other requests if change screens/rebuild widgets.
  • Alex Hartford
    Alex Hartford about 3 years
    Glad you were able to solve it. I would say the approach is dependent on the use case. If maintainState works for you here then I'd say great, it's generally better to use autoDispose if you can. There are definitely times to not use it though.
  • Alex Hartford
    Alex Hartford about 3 years
    Since this solved your issue, you should mark this as the accepted answer.