合并两个可观察变量并返回值作为List,即使一个可观察变量发出onError

时间:2019-04-12 09:28:13

标签: android retrofit2 rx-java2

我试图将两个可观察对象合并到对象列表中,并在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

1 个答案:

答案 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()
}