RxJava2 |如何处理一组 Maybes
RxJava2 | How to process a group Maybes
我正在重构代码以使用 RoomDataBase 和 RxJava2。我有一个数据源,它通过 id 和 returns 获取一行,也许
override fun getByAppWidgetId(appWidgetId: Int): Maybe<LocationWidget> {
return mDB.locationDao().getByAppWidgetId(appWidgetId)
}
在其他地方,我得到一个 appWidgetId
数组,我想为其获取每个 ID 的行条目。我想将所有的 Maybe 组合成一个 Observable 和
private fun hasCurrentLocationWidget(appWidgetIds: IntArray): Single<Boolean> {
observableOfMaybes: Observable // something to hold the maybes we're about to get
for (appWidgetId in appWidgetIds) {
locationMaybe: Maybe<LocationWidget> = dataSource.getByAppWidgetId(appWidgetId)
// -> add each Maybe to `observableOfMaybes`
}
return observableOfMaybes
.subscribeOn(Schedulers.newThread())
// somehow return if any of the `isCurrentLocation` are true
.filter({ location -> location.isCurrentLocation == true })
.toSingle()
}
您可以使用 flatMapMaybe()
创建 Maybes 的 Observable。为此,您需要将 IntArray
转换为 vararg
。
Observable.fromArray(*appWidgetIds.toTypedArray())
.flatMapMaybe { getByAppWidgetId(it) }
我正在重构代码以使用 RoomDataBase 和 RxJava2。我有一个数据源,它通过 id 和 returns 获取一行,也许
override fun getByAppWidgetId(appWidgetId: Int): Maybe<LocationWidget> {
return mDB.locationDao().getByAppWidgetId(appWidgetId)
}
在其他地方,我得到一个 appWidgetId
数组,我想为其获取每个 ID 的行条目。我想将所有的 Maybe 组合成一个 Observable 和
private fun hasCurrentLocationWidget(appWidgetIds: IntArray): Single<Boolean> {
observableOfMaybes: Observable // something to hold the maybes we're about to get
for (appWidgetId in appWidgetIds) {
locationMaybe: Maybe<LocationWidget> = dataSource.getByAppWidgetId(appWidgetId)
// -> add each Maybe to `observableOfMaybes`
}
return observableOfMaybes
.subscribeOn(Schedulers.newThread())
// somehow return if any of the `isCurrentLocation` are true
.filter({ location -> location.isCurrentLocation == true })
.toSingle()
}
您可以使用 flatMapMaybe()
创建 Maybes 的 Observable。为此,您需要将 IntArray
转换为 vararg
。
Observable.fromArray(*appWidgetIds.toTypedArray())
.flatMapMaybe { getByAppWidgetId(it) }