gpt4 book ai didi

flutter - 如何在一个区 block 中收听多个流订阅?

转载 作者:行者123 更新时间:2023-12-04 13:53:06 28 4
gpt4 key购买 nike

我正在尝试创建一个依赖于其他两个集团的集团。例如,我有 Bloc C这取决于 Bloc ABloc B .我正在尝试使用 flutter_bloc 执行以下操作为了实现它:

class BlocC
extends Bloc< BlocCEvent, BlocCState> {
final BlocA blocA;
final BlocC blocB;

StreamSubscription blocASubscription;
StreamSubscription blocBSubscription;

BlocC({
@required this.blocA,
@required this.blocB,
}) : super((blocA.state is blocALoaded &&
blocB.state is blocBLoaded)
? BlocCLoaded(
blocA: (blocA.state as blocALoaded).arrayFromBlocA,
blocB:
(blocB.state as blocBLoaded).arrayFromBlocB,
)
: BlocCLoading()) {

blocASubscription = blocA.stream.listen((state) {
if (state is blocALoaded) {
add(BlocAUpdated((blocA.state as blocALoaded).arrayFromBlocA));
}
});

blocBSubscription = blocB.stream.listen((state) {
if (state is BlocBLoaded) {
add(BlocBUpdated((blocB.state as BlocBLoaded).arrayFromBlocB));
}
});
}

...

@override
Future<void> close() {
blocASubscription.cancel();
BlocBSubscription.cancel();
return super.close();
}
}
问题是我收到以下错误: Bad state: Stream has already been listened to .我在下一个 post 中找到了有关该错误的信息.
我知道错误正在发生,因为一个流一次只能听一个块,而不是多个块。就我而言,流已经在收听 blocA当我试着听 blocB .但是,我不确定如何解决这个问题。
我真的很感激这方面的任何帮助。

最佳答案

您必须将两个流合并为一个,并根据事件类型采取行动:

import 'package:async/async.dart' show StreamGroup;

//...

final blocAStream = blocA.stream;
final blocBStream = blocB.stream;
var blocAandBStreams = StreamGroup.merge([blocAStream, blocBStream]);

blocAandBStream.listen((event){
if(event is BlocAState){
if (event is blocALoaded) { //<-- for readability
add(BlocAUpdated((blocA.state as blocALoaded).arrayFromBlocA));
}
}else if(event is BlocBState){
if (event is BlocBLoaded) {//<-- for readability
add(BlocBUpdated((blocB.state as BlocBLoaded).arrayFromBlocB));
}
}
})

关于flutter - 如何在一个区 block 中收听多个流订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67232114/

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