我有一个从房间数据库获取championList的请求。我只想通过对每个项目使用championId来发出另一个请求。所以我使用了Observable.fromIterable()。我总共有两个请求,它们都返回observable。我将在下面解释我的代码:
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将我的第一个结果保存到map中。在flatMap中,我使用championId发出了我的第二个请求。我还使用map()方法将我的第二个结果保存到map中。在那之后,我只想触发一次订阅方法。但是如果没有toList()方法,则subscribe将由我的列表的长度触发。使用toList()方法,永远不会触发subscribe。我怎么才能修复它?
发布于 2020-02-27 16:33:46
尝试使用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()
})
}https://stackoverflow.com/questions/60428988
复制相似问题