首页 > 解决方案 > 使用 rxJava2 在改造中链接请求并将结果填充到 recyclerview

问题描述

我正在尝试使用 thesportsdb 中的 API 来显示特定联赛的最后一场比赛。在我的 recyclerview 中,我想显示每个团队的团队徽章,但是当我请求 lastmatch API 时,它不包括团队徽章,只有每个团队的 id,如果我想显示徽章,它需要我请求团队包含团队徽章网址的个人资料。

由于我是 rxJava 的新手,所以我仍然熟悉它。一些帖子建议使用平面地图,但对于像我这样的初学者来说实施它有点困难。

这是改造服务:

interface FootballRest {

@GET("eventspastleague.php")
fun getLastmatch(@Query("id") id:String) : Flowable<FootballMatch>

@GET("lookupteam.php")
fun getTeam(@Query("id") id:String) : Flowable<Teams>
}

我使用了存储库模式

class MatchRepositoryImpl(private val footballRest: FootballRest) : MatchRepository {
override fun getFootballMatch(id: String): Flowable<FootballMatch> = footballRest.getLastmatch(id)

override fun getTeams(id: String): Flowable<Teams> = 
footballRest.getTeam(id)
}

这是进行呼叫并将数据发送到视图的演示者:

class MainPresenter(val mView : MainContract.View, val matchRepositoryImpl: MatchRepositoryImpl) : MainContract.Presenter{

val compositeDisposable = CompositeDisposable()

val requestMatch = matchRepositoryImpl.getFootballMatch("4328")
val requestTeam = matchRepositoryImpl.getTeams()

override fun getFootballMatchData() {
    compositeDisposable.add(matchRepositoryImpl.getFootballMatch("4328")
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe{
                mView.displayFootballMatch(it.events)
            })
}

到目前为止,我只显示了最后一场比赛的结果,但我还想在名单上显示徽章球队。

标签: androidkotlinretrofit2rx-java2

解决方案


您可以为此使用与第二个map组合的运算符,然后返回结果。一个简单的例子如下:lastElement().blockingGet()ObservablePair

@Test
public fun test1() {
    Observable.just(1)
            .map {
                // here 'it' variable is calculated already so it can be passed to the second observable
                val result = Observable.just(2).lastElement().blockingGet()
                 Pair<Int, Int>(it, result)
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { t -> System.out.println("First : " + t?.first + ", second : " + t?.second) }

    Thread.sleep(1000)
}

输出

1 2

如果您的第二个Observable取决于第一个的结果,那么只需使用运算符it内部的变量map并将其传递到所需的任何位置。因此,如果使用前面的示例,您的代码可以转换为:

override fun getFootballMatchData() {
    compositeDisposable.add(matchRepositoryImpl.getFootballMatch("4328").toObservable( 
            .map {
                // here 'it' variable is calculated already so it can be passed to the second observable
                val next = matchRepositoryImpl.getTeams(it).toObservable().lastElement().blockingGet()
                Pair<Int, Int>(it, next)
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe{ t ->
                mView.displayFootballMatch(t.first)
                mView.displayBadgeTeam(t.second)
            })
}

推荐阅读