flutterfirebasedartrxdartflutter-streambuilder

Remove Streams from CombineLatestStream - RxDart


I am using:

Code Functionality

  1. I get all my FrediUserGroup data from a provider declared at the beginning of the app.
 var userGroups = Provider.of<List<FrediUserGroup>?>(context);
 FrediUserGroup group = userGroups![widget.groupIndex]; 
  1. I use the group.participantsIds property, that is constantly updated if some id is added/deleted from the database, as an argument for the stream in question:
    StreamBuilder(
        stream: getGroupParticipantsDB(group.participantsIds),
        builder: (BuildContext context, AsyncSnapshot<dynamic> 
            participantDataSnapshot) {
            return MyWidgets() //any widget to display data
        });
  1. Using rxDart, the data from those participants is loaded into a CombineLatestStream
 Stream<List<FrediUser>>? getGroupParticipantsDB(List<String>? participantIds) {
    List<Stream<FrediUser>> streams = [];
    
    participantIds?.forEach((id) {
       var streamToAdd = dbQuery(2, 'users', id).onValue.map((event) => 
       FrediUser.fromMap(event.snapshot.value as Map));
       streams.add(streamToAdd);
    });
    
    return CombineLatestStream.list(streams);}

Problem

Question

How can I delete/reset the CombineLatestStream before calling CombineLatestStream.list(streams) again? Because it is storing the old streams which I no longer need. As it is an immutable list, I cannot clear() it.


Solution

  • According to the docs rxdart

    https://pub.dev/documentation/rxdart/latest/rx/CombineLatestStream-class.html

    If the provided streams is empty, the resulting sequence completes immediately without emitting any items and without any calls to the combiner function.

    and according to the docs of flutter

    https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html

    The data and error fields of snapshots produced are only changed when the state is ConnectionState.active.

    I assume that when you have an empty list of id, CombineLatestStream has an empty list of streams and closes the stream immediately. Since the stream is closed, StreamBuilder doesn't provider new data.

    To rerender your widget with empty array of users try to use a condition like this:

    if (ids.isEmpty) {
      return Stream.value([]);
    }