【发布时间】:2019-10-12 19:50:26
【问题描述】:
我正在尝试创建一个 BLOC,它依赖于另外两个基于时间的块和一个非基于时间的块。我所说的基于时间的意思是,例如他们正在连接远程服务器,所以这需要时间。它的工作原理是这样的:
登录(当然需要一些时间)
如果登录成功
执行另一个过程(这也需要时间。它返回一个未来。)
登录和另一个进程完成后,让页面知道它。
我的 BLOC 取决于这三个:
final UserBloc _userBloc;
final AnotherBloc _anotherBloc;
final FinishBloc _finishBloc;
在映射事件到状态方法中,我应该调度相关事件。但是,如果他们完成了,我不能等待。
_userBloc.dispatch(
Login(),
);
_anotherBloc.dispatch(
AnotherProcess(),
);
//LetThePageKnowIt should work after login and another process
_finishBloc.dispatch(
LetThePageKnowIt(),
);
有没有一种干净的方法可以在发送某些东西之前等待其他一些人?
知道我使用了我不喜欢的方式。在我连接其他集团的主要集团的状态下,我有布尔值。
class CombinerState {
bool isLoginFinished = false;
bool isAnotherProcessFinished = false;
我正在主块的构造函数中监听与时间相关的块的状态。当他们产生“我完成了”时,我只是将布尔值标记为“真”。
MainBloc(
this._userBloc,
this._anotherBloc,
this._pageBloc,
); {
_userBloc.state.listen(
(state) {
if (state.status == Status.finished) {
dispatch(FinishLogin());
}
},
);
_anotherBloc.state.listen(
(state) {
if (state.status == AnotherStatus.finished) {
dispatch(FinishAnotherProcess());
}
},
);
}
我在将 bool 设置为 true 后,为 main bloc 发送另一个事件以检查所有 bool 是否为 true。
else if (event is FinishAnotherProcess) {
newState.isAnotherProcessFinished = true;
yield newState;
dispatch(CheckIfReady());
}
如果布尔值是真的,我调度 LetThePageKnowIt()
else if (event is CheckIfReady) {
if (currentState.isAnotherProcessFinished == true &&
currentState.isLoginFinished == true) {
_pageBloc.dispatch(LetThePageKnowIt());
}
}
我对这段代码不满意。我正在寻找一种方法来等待其他 BLOC 发送“完成”状态。之后我想发送我的 LetThePageKnowIt()
【问题讨论】:
-
你不能创建一个 async 方法来处理你的所有步骤吗?
-
一种异步方法是什么意思?如果您正在谈论在异步方法中调度事件,则将事件映射到状态方法已经是异步的。
-
我的意思是您的步骤如下:
Login (It's of course taking some time) If login is successful Do another process (This is something takes time also. It returns a future.)- 只需阅读您的“登录流”,完成后执行您的第二步 -
在阅读“登录流”时只需使用await for - 完成后只需返回您从第二个“步骤”(无论是什么)获得的
Future -
类似:
Future myMethod() async { await for (var loginItem in loginStream) { do something with loginItem }; return anotherProcess(); }