gpt4 book ai didi

flutter - BehaviorSubject 添加相同的值

转载 作者:行者123 更新时间:2023-12-05 02:43:58 31 4
gpt4 key购买 nike

您好,我有一个具有简单类型 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, exceptthat it never provides two consecutive data events that are equal.That is, errors are passed through to the returned stream, and dataevents are passed through if they are distinct from the most recentlyemitted 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com