Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update streams based on filters in Dart/Flutter

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!

like image 715
ahaese Avatar asked Aug 20 '18 12:08

ahaese


1 Answers

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

like image 57
Rémi Rousselet Avatar answered Dec 08 '22 03:12

Rémi Rousselet