根据Dart / Flutter中的过滤器更新流 [英] Update streams based on filters in Dart/Flutter
问题描述
我有一个BLoC,它消耗原始输入 Stream
(产生JSON对象列表),并使用 StreamTransformer将其转换为可用对象
。 UI将显示该列表。用户可以应用过滤器(本身就是流到BLoC中的流),以便BLoC用相应的 where(...)
语句更新输入流转换器。
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.
问题是:当过滤器更改时,UI不会更新,因为输出流取决于JSON输入流的事件,而不是过滤器流。我的假设是我需要创建自己的流,将输入事件和过滤器事件都转发到该流中,或者我需要在转换后的输入流上重复最后一个事件,以便转换器有机会将其拾取。如何正确完成?一个例子会很有帮助!
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!
推荐答案
您的假设是正确的。您需要创建第三个流,同时接收JSON流和Filter流,并将两者组合成自定义结果。
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.
通常这是通过Stream转换器完成的。使用 myStream.transform
方法。但这有点复杂。
This is usually done with a Stream transformer. Using myStream.transform
method. But this is kinda complicated.
为了使事情变得更加简单,有一个名为 rxdart 基本上是 Stream
的子类,并添加了一些常见的转换器。
To make things far easier, there's a package called rxdart which basically subclass Stream
and adds a few common transformers.
使用rxdart,您可以使用 combineLatest
运算符
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));
});
更多有关reactx运算符的信息此处
More informations on reactivex operators here
这篇关于根据Dart / Flutter中的过滤器更新流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!