Update streams based on filters in Dart/Flutter
Asked Answered
B

1

7

I have a BLoC that consumes a raw input Stream (that yields a list of JSON objects) and transforms it to usable objects using a StreamTransformer. The UI shows that list. The user can apply a filter (itself a stream into the BLoC), such that the BLoC updates the input stream transformer with respective where(...) statements.

The question is: When the filter changes, the UI is not updated because the output stream depends on events of the JSON input stream, not the filter stream. My assumption is I need to either create my own stream into which I forward both input events and filter events, or I need to repeat on the transformed input stream the last event, such that the transformer has a chance to pick it up. How is this done properly? An example would help a lot!

Broadside answered 20/8, 2018 at 12:37 Comment(1)
I removed the "common scenario didn't find it" thing. In general, try to put in your questions only what helps to answer. These kinds of content actually hinder the reader for no real reason.Variorum
H
14

Your assumption is correct. You need to create a third steam that takes both your JSON and Filter streams and combine both into a custom result.

This is usually done with a Stream transformer. Using myStream.transform method. But this is kinda complicated.

To make things far easier, there's a package called rxdart which basically subclass Stream and adds a few common transformers.

Using rxdart, you could create this third stream by using combineLatest operator

Observable<List<String>> list;
Observable<String> filter;

final output = Observable.combineLatest2(filter, list, (String filter, List<String> list) {
  return list.where((str) => str.startsWith(filter));
});

More informations on reactivex operators here

Hedva answered 20/8, 2018 at 12:51 Comment(3)
Thank you! I seem to have no luck using withLatestFrom. Looking at this marbe diagram, it seems what I need is rather combineLatest, because I need to update the stream whenever either stream fires, not just one. But I fail to find the equivalent method in Dart.Broadside
My bad. Fixed with a combineLatest exampleVariorum
Perfect, thanks a lot! Bonus points for linking to the reactivex docs.Broadside

© 2022 - 2024 — McMap. All rights reserved.