0
votes

I have a usecase where I need to get the data from cache and followed by updating cache with data from server. So that when I access cache next time it will have the updated data.

I tried the concat() and merge() operator for combining cache and network call but at client I need only the first value which makes the network call observable getting disposed as soon as cache value is emitted.

Below is the code i am using , Is there any better way to achieve this. Currently I am doing subscription at doOnSuccess method which is not the right way.

class DataKit{
    
    var cachedData: Data? = null
    
    fun getData(): Single<Data> {
     return if(cachedData != null){
             Single.just(cachedData)
                  .doOnSuccess {
                     getPinInfo()
                     .subscribeOn(schedulerProvider.io())
                     .subscribeBy(defaultErrorFun)
                   }
        }else getPinInfo()
    }
    
    
    fun getPinInfo():Single<Data>{
         api.getDataFromServer()
         .doOnSuccess{ cachedData = it}
         .doOnError{cachedData = null}
    }
1

1 Answers

0
votes

I believe you can write it in 2 lines as a sequence without if/else conditions:

   fun getData(): Single<Data> {
       return Maybe.fromOptional(Optional.ofNullable(cachedData))
            .switchIfEmpty(getPinInfo)
}

If you need also to make server call even if cache is existing you can use flatMapSingle operator:

 .flatMapSingle{ getPinInfo }

But I'm not sure that it makes sense, I mean to make additional request just to update a cache value.

You can use Flowable if you need to get a cache value and then update it with value received from the server.