If may is complete, convert may to single from another source

I want to build a repository class that returns single < something >

This class should first check the cache, which returns may < something > if the May is completed, please go to my service and return 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 Javadoc, but there seems to be no converter for this scenario

Is there a good way to deal with it?

Solution

Here are two fairly simple options you can use First, I found it more clear The second benefit is that you will call the network on any errors in the cache

Suppose you return may. From the cache For example, if the value is not found in the cache, it returns may empty()

1) If there is empty space in the stream, switchifempty() will use the standby observable of the calling network If there is no empty 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) When converted to a single (), null may return an error, triggering a network call

override fun getSomething(): Single<Something> {
      return cache.getSomething()
        .toSingle()
        .onErrorResumeNext {
           Feed.getSomething()
        }
  }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>