RxJava2 |如何处理一组Maybes

时间:2018-10-26 08:25:41

标签: android kotlin rx-java2 android-room

我正在重构代码以使用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()
}

1 个答案:

答案 0 :(得分:1)

您可以使用flatMapMaybe()创建Maybes的可观察物。为此,您需要将IntArray强制转换为vararg

Observable.fromArray(*appWidgetIds.toTypedArray())
        .flatMapMaybe { getByAppWidgetId(it) }