Convert Maybe to Single from another source if Maybe completes

Altoyyr :

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
    }
}    

I have searched through the JavaDoc but it does not seem that a transformer for this scenario exists.

Is there a nice way of handling this?

enyciaa :

Here are two fairly simple options you could use. The first I find more explicit. The second has the benefit that you will call the network on any error in the cache.

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) An empty maybe will return an error when cast toSingle(), triggering the network call.

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437359&siteId=1