我试图将两个可观察对象合并到对象列表中,并在ViewModel中进行查看。我通过使用返回Observable<TeamResponse>
的改造函数来做到这一点。我想两次调用该函数,但是当在后端API中找不到对象时,该函数可能会发出错误。
我尝试使用此方法:
val suggestedTeamsList = ArrayList<TeamResponse>()
Observable.just(teamUseCase.getTeamByUserId(player1ID), teamUseCase.getTeamByUserId(player2ID))
.flatMap {
return@flatMap it.subscribeOn(Schedulers.computation())
}.subscribeOn(Schedulers.computation())
.subscribe(object: Observer<TeamResponse> {
override fun onComplete() {
suggestedTeams.postValue(suggestedTeamsList)
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: TeamResponse) {
Log.d("TEST",t.teamName)
suggestedTeamsList.add(t)
}
override fun onError(e: Throwable) {
Log.d("TEST",e.message)
suggestedTeams.postValue(suggestedTeamsList)
}
})
它可以工作,但是我更希望获得结果作为列表,即使一个函数发出onError,在这种情况下,列表也只有1个对象。或者,也许有人有一个更好的主意,如何以一种好的方法来处理它?可能在两种情况下方法都返回onError
答案 0 :(得分:2)
您可以使用Observable.zip。 EG:
val teamResponse = TeamResponse()
fun loadPlayers() {
val first = teamUseCase.getTeamByUserId(player1ID)
.onErrorResumeNext { t: Throwable -> Observable.just( teamResponse ) }
val second = teamUseCase.getTeamByUserId(player2ID)
.onErrorResumeNext { t: Throwable -> Observable.just( teamResponse ) }
Observable.zip(first, second, BiFunction<TeamResponse, TeamResponse, List<TeamResponse>> { t1, t2 ->
val suggestedTeamsList = mutableListOf<TeamResponse>()
if (t1 !== teamResponse) {
suggestedTeamsList.add(t1)
}
if (t2 !== teamResponse) {
suggestedTeamsList.add(t2)
}
suggestedTeamsList
})
.subscribeOn()
}