bufferapp / clean-architecture-components-boilerplate

A fork of our clean architecture boilerplate, this time using the Android Architecture Components
MIT License
1.28k stars 178 forks source link

saveBufferoos is called even when data is retrieved from cache #15

Open joreilly opened 6 years ago

joreilly commented 6 years ago

In the following code saveBufferoos is called even when data is retrieved from cache (db)....for relatively large amounts of data this can be pretty time consuming.

    override fun getBufferoos(): Flowable<List<Bufferoo>> {
        return factory.retrieveCacheDataStore().isCached()
                .flatMapPublisher {
                    factory.retrieveDataStore(it).getBufferoos()
                }
                .flatMap {
                    Flowable.just(it.map { bufferooMapper.mapFromEntity(it) })
                }
                .flatMap {
                    saveBufferoos(it).toSingle { it }.toFlowable()
                }
    }
joreilly commented 6 years ago

Following is a variation that will only save when remote data is fetched (though is missing right now check for cache being invalid)


    override fun getBufferoos(): Flowable<List<Bufferoo>> {
        return Flowable.concatArray(getBufferoosFromCache(), getBufferoosFromRemote())
                .firstElement()
                .toFlowable()
    }

    fun getBufferoosFromCache(): Flowable<List<Bufferoo>> {
        return factory.retrieveCacheDataStore().getBufferoos()
                .filter { it.isNotEmpty() }
    }

    fun getBufferoosFromRemote(): Flowable<List<Bufferoo>> {
        return factory.retrieveRemoteDataStore().getBufferoos()
                .flatMap {
                    saveBufferoos(it).toSingle { it }.toFlowable()
                }
    }
joreilly commented 6 years ago

What I've ended up using in my own code is Single source of truth approach where higher layers always subscribe to db updates (though still through repository interface) and any remote fetches will just update db (which in turn triggers update.....have modified queries in Room DAO to return a Flowable)