我正在重构代码以使用RoomDataBase和RxJava2。我有一个数据源,该数据源按ID提取一行并返回Maybe
override fun getByAppWidgetId(appWidgetId: Int): Maybe<LocationWidget> {
return mDB.locationDao().getByAppWidgetId(appWidgetId)
}
在其他地方,我得到了一个appWidgetId
数组,我想为其获取每个ID的行条目。我想将所有Maybes合并为一个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()
}
答案 0 :(得分:1)
您可以使用flatMapMaybe()
创建Maybes的可观察物。为此,您需要将IntArray
强制转换为vararg
。
Observable.fromArray(*appWidgetIds.toTypedArray())
.flatMapMaybe { getByAppWidgetId(it) }