I would like to build a Repository class that returns a Single<Something>.

The class should first look in a Cache which returns Maybe<Something> and if the Maybe completes go off to my Service that returns Single<Something>

interface Cache {
    fun getSomething(): Maybe<Something>   
}

interface Service {
    fun getSomething(): Single<Something>   
}

class Repository (
    private val cache: Cache,
    private val service: Service
) {

    fun getSomething(): Single<Something> {
      return cache.getSomething()
               .????(feed.getSomething()) //onCompleteTransformToSingle() or similar
    }
}    

我已经搜索了JavaDoc,但似乎不存在这种情况下的转换器.

Is there a nice way of handling this?

推荐答案

下面是两个非常简单的选项.第一个我发现更明确.第二个好处是,当缓存中出现任何错误时,您都可以调用网络.

These assume a Maybe is returned from the cache. For example if no value is found in the cache, return Maybe.empty()

1) If there is an empty in the stream, switchIfEmpty() will use the alternate observable which calls the network. If no empty is in the stream, the network will never be called.

override fun getSomething(): Single<Something> {
      return cache.getSomething()
        .switchIfEmpty(
          Maybe.defer {
            feed.getSomething().toMaybe()
          }
        )
        .toSingle()
  }

2) 当强制转换为Single()时,空值可能会返回一个错误,从而触发网络调用.

override fun getSomething(): Single<Something> {
      return cache.getSomething()
        .toSingle()
        .onErrorResumeNext {
           feed.getSomething()
        }
  }

Kotlin相关问答推荐

将带大括号和不带大括号的Lambda值赋给@Composable函数

在Kotlin中的嵌套when语句中,else块是强制性的吗?

同时也是一个字符串的 Kotlin 枚举

Kotlin 如何使用其 get 函数在内部检索映射值

kotlin 父类具有依赖于抽象变量的变量

我们应该在 Effect 和 Either 之间 Select 哪个作为我们业务服务的返回类型?

奇怪的 cotlin check Not Null 参数错误

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

基类中的 ViewModelProviders.get(...)

jetpack compose 将参数传递给 viewModel

`DataBindingUtil` 中的 `bind`、`inflate` 和 `setContentView` 有什么区别

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

取消信号上的kotlin流量采集

Kotlin - 来自 KType 的 KClass<*>

RecyclerView SnapHelper无法显示第一个/最后一个元素

Kotlin - 是否可以在类中的 init 块之前初始化伴随对象?

接口中的属性不能有支持字段

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

Recyclerview: listen to padding click events