Arunachalam k
Arunachalam k

Reputation: 744

Problem when integrate caching with concat operator in Rx java

Implemented Caching by the following link: https://blog.mindorks.com/implement-caching-in-android-using-rxjava-operators

fun getSavedAddressList(): Maybe<List<SavedAddress>?>? {
    return Observable.concat(
            getAddressListMemory(),
            getAddressListDatabase(),
            getAddressListNetwork()).firstElement()
}

   fun getAddressListDatabase(): Observable<List<SavedAddress>?> {
        return Observable.create(ObservableOnSubscribe { emitter: ObservableEmitter<List<SavedAddress>?> ->
            val list: ArrayList<SavedAddress> = addressDao.getAddressList() as ArrayList<SavedAddress>
            if (list.isNotEmpty()) {
                emitter.onNext(list)
            }
            emitter.onComplete()
            if (list.isNotEmpty())


    getAddressListNetwork().subscribeOn(schedulerProvider.io())?.observeOn(schedulerProvider.io())?.subscribe()
        })
    }

items in the database are retrieving perfectly after storing into database

problem is network calling is not happening after getting a list from database

I want to get three data source sequentially one after another and store latest data in the database

Upvotes: 0

Views: 52

Answers (1)

ExpensiveBelly
ExpensiveBelly

Reputation: 454

First of all, you're leaking the getAddressListNetwork Disposable in there because you are trying to do too much inside the getAddressListDatabase.

I think what you want is this:

fun getSavedAddressList(): Observable<List<SavedAddress>> {
    return Observable.concat(
            getAddressListMemory(),
            getAddressListDatabase(),
            getAddressListNetwork()).distinctUntilChanged())
}

This will always try to fetch the addresses from the 3 sources, and only emitting if the data is different than the previous emission, meaning the data is "fresher".

To be honest with you, I think you need to have a look at the concept of "stale data" and "cache invalidation".

Upvotes: 1

Related Questions