Merge multiple GetX controllers into one stream

Viewed 271

I want to use multiple GetX controllers in my widget. The StreamBuilder of the async package offers the possibility to combine streams like in the code below. Is there any way to use this approach with the GetX? I would not like to nest the GetX as this leads to ugly code.

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<dynamic>>(
      stream: CombineLatestStream.list(
        [
          _profileStore.getProfileStream(),
          _journalStore.getJournalStream(),
        ],
      ),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Center(child: CircularProgressIndicator());
        }

        final Profile profile = snapshot.data![0];
        final List<Dream> journal = snapshot.data![1];
        ...
      }
    );
  }

My current widget with GetX looks like this.

  @override
  Widget build(BuildContext context) {
        return GetX<ProfileStore>(
          builder: (store) {
            return Text('${store.profile.value.username}');
          }
        );
  }
2 Answers

Use the CombineLatestStream.list([]) function from rxdart documentation to create a new stream from it.

Stream stream = CombineLatestStream.list([...]);

Then, bind that new stream to the variable or observable you want to update:

var.bindStream(stream);

Lars above mentioned the most of thing, just want to add my way of updating variable using GetX

CombineLatestStream combinedStream =
          CombineLatestStream.list(multipleStreams);

      try {
        combinedStream.listen((values) {
          Map<String, dynamic> localMap = {};

          (values as List).forEach((element) {
            localMap[key]] = element;
          });

          rxVar.addAll(localMap);
        });
      } catch (e) {
        log("Err : binding stream $e");
      }
Related