Android RxJava toList()不触发subscribe()方法(带Room)
我请求从房间数据库中获取championList。我只想用championId对每一件物品提出另一个请求。所以我使用了Observable.fromIterable()。我总共有两个请求,它们都返回可观察的。我将在下面解释我的代码:Android RxJava toList()不触发subscribe()方法(带Room),android,kotlin,rx-java,android-room,Android,Kotlin,Rx Java,Android Room,我请求从房间数据库中获取championList。我只想用championId对每一件物品提出另一个请求。所以我使用了Observable.fromIterable()。我总共有两个请求,它们都返回可观察的。我将在下面解释我的代码: private fun getData() { appDatabase.tierListDao().getChampionOfTier() .subscribeOn(Schedulers.io()) .
private fun getData() {
appDatabase.tierListDao().getChampionOfTier()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.concatMap {
Observable.fromIterable(it)
}
.doOnNext {
tierListMap[it.championTable!!.id!!] = TierChampionAndCounterPicks().apply {
tierAndChampion = it
}
}
.flatMap { tierAndChampion ->
appDatabase.counterPicksDao()
.getCounterPicksWithChampionId(tierAndChampion.championTable!!.id!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.map {
tierListMap[it.first().counterPicksTable?.low_level_champion_id]?.apply {
counterPicksTableList = it
}?.let { tier ->
tierList.add(tier)
}
tierList
}
.toList()
.subscribe({
tierListAdapter = TierListAdapter(context!!, tierList)
tierListRv.adapter = tierListAdapter
}, {
it.printStackTrace()
})
}
我正在用doOnNext将我的第一个结果保存到地图中。对于flatMap,我使用championId提出第二个请求。我还使用map()方法将第二个结果保存到map中。之后,我只想触发订阅方法一次。但是如果没有toList()方法,subscribe将由我的列表的长度触发。使用toList()方法,永远不会触发订阅。如何修复它?尝试使用take(1)而不是toList(),但您应该尽量不要将结果保存在流外,而是在流内执行
编辑此解决方案应按您的需要工作:
private fun getData() {
appDatabase.tierListDao().getChampionOfTier()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.switchMap{ champions ->
val tierChamps = champions.map {
TierChampionAndCounterPicks().apply {
tierAndChampion = it
}
}
Observable.fromIterable(tierChamps).switchMap { tierChamp ->
appDatabase.counterPicksDao()
.getCounterPicksWithChampionId(tierChamp.championTable!!.id!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { counterPicksTableList ->
tierChamp.apply {
counterPicks = counterPicksTableList
}
}
}
}
.toList()
.subscribe({ tierList ->
tierListAdapter = TierListAdapter(context!!, tierList)
tierListRv.adapter = tierListAdapter
}, {
it.printStackTrace()
})
}
当我使用take(1)时,屏幕上只显示列表的第一项。如果没有toList()和take(1),则每次触发订阅时,都会将新项目添加到列表中。所以,对于take(1),只将第一项添加到列表中。感谢您的编辑,它使我的代码更短,但在toList()之后它不会触发任何内容。这太奇怪了,我想我们应该写些东西来完成toList()过程,但我不知道该写什么。我的意思是,它不会在toList()之后触发任何东西,因为toList()进程没有完成,可能流中有一些错误。尝试在getCounterPicksWithChampionId上添加onError,看看是否一切正常GetCouterPickSwithChampionId工作正常,它没有输入onError(),并且它正确地包含了我的列表项。因此,如果你有其他想法要解决,我也可以试试。@BurcuTOPÇU要获得更多帮助,我需要你的应用程序的详细信息,可能是GetChampionOffier()有问题,因为我自己制作了一个小样本,一切正常。尝试调试这个地方“counterPicks=counterPicksTableList”,并查看它是否为getChampionOfTier()中的每个champion运行。