【发布时间】:2018-04-08 23:01:14
【问题描述】:
使用 Jake Wharton 的 Managing State with RxJava 模式。
我将两个 api 调用组合在一起以并行执行。
当两者都完成时,我如何发出“成功”项目?
请参见下面代码中的 cmets。
谢谢!
主调用函数:
Observable
.just(UpdatePicEvent(userId, file))
.compose(updatePic()) <-- Handles updating pic, emits models consumed by UI
.mergeWith(
Observable
.just(UpdateProfileEvent(..params...))
.compose(updateProfile()) <-- Handles updating other settings, emits models consumed by UI
)
// TODO Need to add something to emit a Success() model item when both actions above have completed
.subscribe(...pass models to UI...)
updatePic()
fun updatePic(): ObservableTransformer<UpdatePicEvent, ProfileSettingsModel> {
return ObservableTransformer {
it.flatMap {
api.uploadProfilePic(it.userId, it.pic)
.map { UpdatePicSuccessful(it) as ProfileSettingsModel }
.onErrorReturn { UpdatePicError(it) as ProfileSettingsModel }
.startWith(UpdatePicInProgress() as ProfileSettingsModel)
}
}
}
updateProfile()
fun updateProfile(): ObservableTransformer<UpdateProfileEvent, ProfileSettingsModel> {
return ObservableTransformer {
it.flatMap {
api
.updateUser(...params...)
.subscribeOn(Schedulers.io())
.map { UpdateProfileSuccessful(it) as ProfileSettingsModel }
.onErrorReturn { UpdateProfileError(it) as ProfileSettingsModel }
.observeOn(AndroidSchedulers.mainThread())
.startWith(UpdateProfileInProgress() as ProfileSettingsModel)
}
}
}
【问题讨论】:
-
你最终的成功是否需要从结果中得到什么?你想通过你发出的最后一件事来完成什么?另外,您是否需要按顺序调用
updatePic和updateProfile(您似乎不需要,因为您合并了……但请确保给您一个好的答案) -
@marianosimone “你最终的成功是否需要从结果中获得任何东西?”在这种情况下,没有。 “你想通过你发出的最后一件事来完成什么?”我正在使用密封类
ProfileSettingsModel来传达事务的状态。我要发出的最后一件事是表示两个 API 调用都已成功完成。谢谢! -
以上答案能解决你的问题吗?