您好,我有一个具有简单类型 int 的 BehaviorSubject,我将值 5 添加到它,然后添加另一个值 5。流监听器向我发送了两个事件。 如果值等于最后一个值,如何强制检查值并且不发送事件。 示例代码:
class TestBloc {
TestBloc(){
testBehavior.stream.listen((event) {
print('Event value = $event');
});
addValueToStream();
addValueToStream();
}
final testBehavior = BehaviorSubject<int>();
void addValueToStream() {
testBehavior.add(5);
}
}
最佳答案
您正在寻找的是 BehaviorSubject()
的 distinct()
方法。
从文档中看一下:
Skips data events if they are equal to the previous data event.
The returned stream provides the same events as this stream, except that it never provides two consecutive data events that are equal. That is, errors are passed through to the returned stream, and data events are passed through if they are distinct from the most recently emitted data event.
下面是你如何实现它:
class TestBloc {
TestBloc() {
testBehavior.distinct((a, b) => a == b).listen((event) {
print('Event value = $event');
});
addValueToStream();
addValueToStream();
}
final testBehavior = BehaviorSubject<int>();
void addValueToStream() {
testBehavior.add(5);
}
}
关于flutter - BehaviorSubject 添加相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66671769/