android - 使用 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)
})
}
到目前为止,我只显示了最后一场比赛的结果,但我还想在名单上显示徽章球队。
解决方案
您可以为此使用与第二个map
组合的运算符,然后返回结果。一个简单的例子如下:lastElement().blockingGet()
Observable
Pair
@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)
})
}
推荐阅读
- python-3.x - 不使用 numpy 打印下三角矩阵
- c# - 无法连接到 C# Visual Studio 中的 sql 无法登录
- java - PHP和Java之间的LZString压缩数据
- php - 桌面/Webapp 共享数据库覆盖重复键上的数据
- c++ - 获取类成员函数的地址并从指针调用它
- tensorflow - 安装包“conda-forge::astor-0.7.1-py_0”时出错
- java - 如何使用 Apache POI 将图片大小调整为段落大小?
- python - 某些 Altair 3.0 图表未在 Google Colab 中显示
- android-emulator - Android Emulator 和 Google Play Store 显示消息应用程序不兼容
- ruby - 有没有最简单的方法来增加字符串的价值?