只是问我是否做对了,因为我不知道为什么doOnComplete
尚未完成时为何doOnNext
正在呼叫?
这就是为什么,我要问如何等待doOnNext
中的所有任务
致电doOnComplete
之前是什么?
doOnNext
内部的另一项任务是将数据插入数据库。
private val disposable = CompositeDisposable()
val branchUser : Observable<BranchUserResponse> = getApi().getBranchUser()
val areaUser : Observable<AreaUserResponse> = getApi().getAreaUser()
val regionalUser : Observable<RegionalUserResponse> = getApi().getRegionalUser()
disposable.add(
Observable.merge(branchUser, areaUser, regionalUser)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { it ->
when (it) {
is BranchUserResponse -> {
branchUserViewModel.addAll()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
Log.i(TAG, "addAll success")
// the doOnComplete is already called before the Log here is call.
// Same with the other condition.
// What I want is to call this first before the doOnComplete or doFinally.
},
{
Log.e(TAG, "addAll failed", it)
}
)
}
is AreaUserResponse -> {
// some stuff here...
}
is RegionalUserResponse -> {
// some stuff here...
}
}
}
.doOnComplete {
Log.i(TAG, "Complete")
}
.doFinally {
Log.i(TAG, "Finally")
}
.subscribe()
)
感谢您的帮助,谢谢。
答案 0 :(得分:1)
如果要在rx-stuff
中指定的所有分支中执行doOnNext
,则必须将doOnNext
更改为flatMap
:
private val disposable = CompositeDisposable()
val branchUser : Observable<BranchUserResponse> = getApi().getBranchUser()
val areaUser : Observable<AreaUserResponse> = getApi().getAreaUser()
val regionalUser : Observable<RegionalUserResponse> = getApi().getRegionalUser()
disposable.add(
Observable.merge(branchUser, areaUser, regionalUser)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { it ->
when (it) {
is BranchUserResponse -> {
branchUserViewModel.addAll()
}
is AreaUserResponse -> {
// some stuff here...
}
is RegionalUserResponse -> {
// some stuff here...
}
}
}
.doOnComplete {
Log.i(TAG, "Complete")
}
.doFinally {
Log.i(TAG, "Finally")
}
.subscribe()
)