Giter VIP home page Giter VIP logo

rxcache's Introduction

⚠️ This repository is no longer mantained consider using Room as an alternative ⚠️

Downloads

Android Arsenal

RxCache

中文文档

For a more reactive approach go here.

The goal of this library is simple: caching your data models like Picasso caches your images, with no effort at all.

Every Android application is a client application, which means it does not make sense to create and maintain a database just for caching data.

Plus, the fact that you have some sort of legendary database for persisting your data does not solves by itself the real challenge: to be able to configure your caching needs in a flexible and simple way.

Inspired by Retrofit api, RxCache is a reactive caching library for Android and Java which turns your caching needs into an interface.

When supplying an observable, single, maybe or flowable (these are the supported Reactive types) which contains the data provided by an expensive task -probably an http connection, RxCache determines if it is needed to subscribe to it or instead fetch the data previously cached. This decision is made based on the providers configuration.

Observable<List<Mock>> getMocks(Observable<List<Mock>> oMocks);

Setup

Add the JitPack repository in your build.gradle (top level module):

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

And add next dependencies in the build.gradle of the module:

dependencies {
    compile "com.github.VictorAlbertos.RxCache:runtime:1.8.3-2.x"
    compile "io.reactivex.rxjava2:rxjava:2.1.6"
}

Because RxCache uses internally Jolyglot to serialize and deserialize objects, you need to add one of the next dependency to gradle.

dependencies {
    // To use Gson 
    compile 'com.github.VictorAlbertos.Jolyglot:gson:0.0.4'
    
    // To use Jackson
    compile 'com.github.VictorAlbertos.Jolyglot:jackson:0.0.4'
    
    // To use Moshi
    compile 'com.github.VictorAlbertos.Jolyglot:moshi:0.0.4'
}

Usage

Define an interface with as much methods as needed to create the caching providers:

interface Providers {

        @ProviderKey("mocks")
        Observable<List<Mock>> getMocks(Observable<List<Mock>> oMocks);
    
        @ProviderKey("mocks-5-minute-ttl")
        @LifeCache(duration = 5, timeUnit = TimeUnit.MINUTES)
        Observable<List<Mock>> getMocksWith5MinutesLifeTime(Observable<List<Mock>> oMocks);
    
        @ProviderKey("mocks-evict-provider")
        Observable<List<Mock>> getMocksEvictProvider(Observable<List<Mock>> oMocks, EvictProvider evictProvider);
    
        @ProviderKey("mocks-paginate")
        Observable<List<Mock>> getMocksPaginate(Observable<List<Mock>> oMocks, DynamicKey page);
    
        @ProviderKey("mocks-paginate-evict-per-page")
        Observable<List<Mock>> getMocksPaginateEvictingPerPage(Observable<List<Mock>> oMocks, DynamicKey page, EvictDynamicKey evictPage);
        
        @ProviderKey("mocks-paginate-evict-per-filter")
        Observable<List<Mock>> getMocksPaginateWithFiltersEvictingPerFilter(Observable<List<Mock>> oMocks, DynamicKeyGroup filterPage, EvictDynamicKey evictFilter);
}

RxCache exposes evictAll() method to evict the entire cache in a row.

RxCache accepts as argument a set of classes to indicate how the provider needs to handle the cached data:

  • A Reactive type is the only object required to create a provider. This Reactive type must be equal to the one specified by the returning value of the provider.
  • EvictProvider allows to explicitly evict all the data associated with the provider.
  • @ProviderKey is an annotation for provider methods that is highly recommended to use and proguard users MUST use this annotation, if not used the method names will be used as provider keys (cache keys) and proguard users will quickly run into problems, please see Proguard for detailed information. Using the annotaiton is also useful when not using Proguard as it makes sure you can change your method names without having to write a migration for old cache files.
  • EvictDynamicKey allows to explicitly evict the data of an specific DynamicKey.
  • EvictDynamicKeyGroup allows to explicitly evict the data of an specific DynamicKeyGroup.
  • DynamicKey is a wrapper around the key object for those providers which need to handle multiple records, so they need to provide multiple keys, such us endpoints with pagination, ordering or filtering requirements. To evict the data associated with one particular key use EvictDynamicKey.
  • DynamicKeyGroup is a wrapper around the key and the group for those providers which need to handle multiple records grouped, so they need to provide multiple keys organized in groups, such us endpoints with filtering AND pagination requirements. To evict the data associated with the key of one particular group, use EvictDynamicKeyGroup.

Supported annotations:

Build an instance of Providers and use it

Finally, instantiate the Providers interface using RxCache.Builder and supplying a valid file system path which would allow RxCache to write on disk.

File cacheDir = getFilesDir();
Providers providers = new RxCache.Builder()
                            .persistence(cacheDir, new GsonSpeaker())
                            .using(Providers.class);

Putting It All Together

interface Providers {

    @ProviderKey("mocks-evict-provider")
    Observable<List<Mock>> getMocksEvictProvider(Observable<List<Mock>> oMocks, EvictProvider evictProvider);

    @ProviderKey("mocks-paginate-evict-per-page")
    Observable<List<Mock>> getMocksPaginateEvictingPerPage(Observable<List<Mock>> oMocks, DynamicKey page, EvictDynamicKey evictPage);

    @ProviderKey("mocks-paginate-evict-per-filter")
    Observable<List<Mock>> getMocksPaginateWithFiltersEvictingPerFilter(Observable<List<Mock>> oMocks, DynamicKeyGroup filterPage, EvictDynamicKey evictFilter);
}
public class Repository {
    private final Providers providers;

    public Repository(File cacheDir) {
        providers = new RxCache.Builder()
                .persistence(cacheDir, new GsonSpeaker())
                .using(Providers.class);
    }

    public Observable<List<Mock>> getMocks(final boolean update) {
        return providers.getMocksEvictProvider(getExpensiveMocks(), new EvictProvider(update));
    }

    public Observable<List<Mock>> getMocksPaginate(final int page, final boolean update) {
        return providers.getMocksPaginateEvictingPerPage(getExpensiveMocks(), new DynamicKey(page), new EvictDynamicKey(update));
    }

    public Observable<List<Mock>> getMocksWithFiltersPaginate(final String filter, final int page, final boolean updateFilter) {
        return providers.getMocksPaginateWithFiltersEvictingPerFilter(getExpensiveMocks(), new DynamicKeyGroup(filter, page), new EvictDynamicKey(updateFilter));
    }

    //In a real use case, here is when you build your observable with the expensive operation.
    //Or if you are making http calls you can use Retrofit to get it out of the box.
    private Observable<List<Mock>> getExpensiveMocks() {
        return Observable.just(Arrays.asList(new Mock("")));
    }
}

Use cases

  • Using classic API RxCache for read actions with little write needs.
  • Using actionable API RxCache, exclusive for write actions.

Classic API RxCache:

Following use cases illustrate some common scenarios which will help to understand the usage of DynamicKey and DynamicKeyGroup classes along with evicting scopes.

List

List without evicting:

Observable<List<Mock>> getMocks(Observable<List<Mock>> oMocks);

List evicting:

Observable<List<Mock>> getMocksEvictProvider(Observable<List<Mock>> oMocks, EvictProvider evictProvider);

Runtime usage:

//Hit observable evicting all mocks
getMocksEvictProvider(oMocks, new EvictProvider(true))

//This line throws an IllegalArgumentException: "EvictDynamicKey was provided but not was provided any DynamicKey"
getMocksEvictProvider(oMocks, new EvictDynamicKey(true))

List Filtering

List filtering without evicting:

Observable<List<Mock>> getMocksFiltered(Observable<List<Mock>> oMocks, DynamicKey filter);

List filtering evicting:

Observable<List<Mock>> getMocksFilteredEvict(Observable<List<Mock>> oMocks, DynamicKey filter, EvictProvider evictDynamicKey);

Runtime usage:

//Hit observable evicting all mocks using EvictProvider
getMocksFilteredEvict(oMocks, new DynamicKey("actives"), new EvictProvider(true))

//Hit observable evicting mocks of one filter using EvictDynamicKey
getMocksFilteredEvict(oMocks, new DynamicKey("actives"), new EvictDynamicKey(true))

//This line throws an IllegalArgumentException: "EvictDynamicKeyGroup was provided but not was provided any Group"
getMocksFilteredEvict(oMocks, new DynamicKey("actives"), new EvictDynamicKeyGroup(true))

List Paginated with filters

List paginated with filters without evicting:

Observable<List<Mock>> getMocksFilteredPaginate(Observable<List<Mock>> oMocks, DynamicKey filterAndPage);

List paginated with filters evicting:

Observable<List<Mock>> getMocksFilteredPaginateEvict(Observable<List<Mock>> oMocks, DynamicKeyGroup filterAndPage, EvictProvider evictProvider);

Runtime usage:

//Hit observable evicting all mocks using EvictProvider
getMocksFilteredPaginateEvict(oMocks, new DynamicKeyGroup("actives", "page1"), new EvictProvider(true))

//Hit observable evicting all mocks pages of one filter using EvictDynamicKey
getMocksFilteredPaginateEvict(oMocks, new DynamicKeyGroup("actives", "page1"), new EvictDynamicKey(true))

//Hit observable evicting one page mocks of one filter using EvictDynamicKeyGroup
getMocksFilteredPaginateInvalidate(oMocks, new DynamicKeyGroup("actives", "page1"), new EvictDynamicKeyGroup(true))

As you may already notice, the whole point of using DynamicKey or DynamicKeyGroup along with Evict classes is to play with several scopes when evicting objects.

The above examples declare providers which their method signature accepts EvictProvider in order to be able to concrete more specifics types of EvictProvider at runtime.

But I have done that for demonstration purposes, you always should narrow the evicting classes in your method signature to the type which you really need. For the last example, I would use EvictDynamicKey in production code, because this way I would be able to paginate the filtered items and evict them per its filter, triggered by a pull to refresh for instance.

Nevertheless, there are complete examples for Android and Java projects.

Actionable API RxCache:

Limitation: This actionable API only support Observable as Reactive type.

This actionable api offers an easy way to perform write operations using providers. Although write operations could be achieved using the classic api too, it's much complex and error-prone. Indeed, the Actions class it's a wrapper around the classic api which play with evicting scopes and lists.

In order to use this actionable api, first you need to add the repository compiler as a dependency to your project using an annotation processor. For Android, it would be as follows:

Add this line to your root build.gradle:

dependencies {
     // other classpath definitions here
     classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
 }

Then make sure to apply the plugin in your app/build.gradle and add the compiler dependency:

apply plugin: 'com.neenbedankt.android-apt'

dependencies {
    // apt command comes from the android-apt plugin
    apt "com.github.VictorAlbertos.RxCache:compiler:1.8.3-2.x"
}

After this configuration, every provider annotated with @Actionable annotation will expose an accessor method in a new generated class called with the same name as the interface, but appending an 'Actionable' suffix.

The order in the params supplies must be as in the following example:

public interface RxProviders {
    @Actionable
    Observable<List<Mock.InnerMock>> mocks(Observable<List<Mock.InnerMock>> message, EvictProvider evictProvider);

    @Actionable
    Observable<List<Mock>> mocksDynamicKey(Observable<List<Mock>> message, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey);

    @Actionable
    Observable<List<Mock>> mocksDynamicKeyGroup(Observable<List<Mock>> message, DynamicKeyGroup dynamicKeyGroup, EvictDynamicKeyGroup evictDynamicKey);
}

The observable value must be a List, otherwise an error will be thrown.

The previous RxProviders interface will expose the next accessors methods in the generated RxProvidersActionable class.

RxProvidersActionable.mocks(RxProviders proxy);
RxProvidersActionable.mocksDynamicKey(RxProviders proxy, DynamicKey dynamicKey);
RxProvidersActionable.mocksDynamicKeyGroup(RxProviders proxy, DynamicKeyGroup dynamicKeyGroup);

These methods return an instance of the Actions class, so now you are ready to use every write operation available in the Actions class. It is advisable to explore the ActionsTest class to see what action fits better for your case. If you feel that some action has been missed please don't hesitate to open an issue to request it.

Some actions examples:

ActionsProviders.mocks(rxProviders)
    .addFirst(new Mock())
    .addLast(new Mock())
    //Add a new mock at 5 position
    .add((position, count) -> position == 5, new Mock())

    .evictFirst()
    //Evict first element if the cache has already 300 records
    .evictFirst(count -> count > 300)
    .evictLast()
    //Evict last element if the cache has already 300 records
    .evictLast(count -> count > 300)
    //Evict all inactive elements
    .evictIterable((position, count, mock) -> mock.isInactive())
    .evictAll()

    //Update the mock with id 5
    .update(mock -> mock.getId() == 5, mock -> {
        mock.setActive();
        return mock;
    })
    //Update all inactive mocks
    .updateIterable(mock -> mock.isInactive(), mock -> {
        mock.setActive();
        return mock;
    })
    .toObservable()
    .subscribe(processedMocks -> {})

Every one of the previous actions will be execute only after the composed observable receives a subscription. This way, the underliyng provider cache will be modified its elements without effort at all.

Migrations

RxCache provides a simple mechanism for handling migrations between releases.

You need to annotate your providers interface with @SchemeMigration. This annotation accepts an array of @Migration annotations, and, in turn, @Migration annotation accepts both, a version number and an array of Classes which will be deleted from persistence layer.

@SchemeMigration({
            @Migration(version = 1, evictClasses = {Mock.class}),
            @Migration(version = 2, evictClasses = {Mock2.class}),
            @Migration(version = 3, evictClasses = {Mock3.class})
    })
interface Providers {}

You want to annotate a new migration only when a new field has been added in a class model used by RxCache.

Deleting classes or deleting fields of classes would be handle automatically by RxCache, so you don't need to annotate a new migration when a field or an entire class has been deleted.

For instance:

A migration was added at some point. After that, a second one was added eventually.

@SchemeMigration({
            @Migration(version = 1, evictClasses = {Mock.class}),
            @Migration(version = 2, evictClasses = {Mock2.class})
    })
interface Providers {}

But now Mock class has been deleted from the project, so it is impossible to reference its class anymore. To fix this, just delete the migration annotation.

@SchemeMigration({
            @Migration(version = 2, evictClasses = {Mock2.class})
    })
interface Providers {}

Because RxCache has an internal process to clean memory when it is required, the data will be evicted eventually.

Encryption

RxCache provides a simple mechanism to encrypt the data.

You need to annotate your providers interface with @EncryptKey. This annotation accepts a string as the key necessary to encrypt/decrypt the data. But you will need to annotate your provider's records with @Encrypt in order to saved the data encrypted. If no @Encrypt is set, then no encryption will be held.

Important: If the value of the key supplied on @EncryptKey is modified between compilations, then the previous persisted data will not be able to be evicted/retrieved by RxCache.

@EncryptKey("myStrongKey-1234")
interface Providers {
        @Encrypt
        Observable<List<Mock>> getMocksEncrypted(Observable<List<Mock>> oMocks);

        Observable<List<Mock>> getMocksNotEncrypted(Observable<List<Mock>> oMocks);
}

Configure general behaviour

RxCache allows to set certain parameters when building the providers instance:

Configure the limit in megabytes for the data to be persisted

By default, RxCache sets the limit in 100 megabytes, but you can change this value by calling setMaxMBPersistenceCache method when building the provider instance.

new RxCache.Builder()
            .setMaxMBPersistenceCache(maxMgPersistenceCache)
            .persistence(cacheDir)
            .using(Providers.class);

This limit ensure that the disk will no grow up limitless in case you have providers with dynamic keys which values changes dynamically, like filters based on gps location or dynamic filters supplied by your back-end solution.

When this limit is reached, RxCache will not be able to persist in disk new data. That's why RxCache has an automated process to evict any record when the threshold memory assigned to the persistence layer is close to be reached, even if the record life time has not been fulfilled.

But provider's record annotated with @Expirable annotation and set its value to false will be excluded from the process.

interface Providers {
    @Expirable(false)
    Observable<List<Mock>> getMocksNotExpirable(Observable<List<Mock>> oMocks);
}

Use expired data if loader not available

By default, RxCache will throw a RuntimeException if the cached data has expired and the data returned by the observable loader is null, preventing this way serving data which has been marked as evicted.

You can modify this behaviour, allowing RxCache serving evicted data when the loader has returned null values, by setting as true the value of useExpiredDataIfLoaderNotAvailable

new RxCache.Builder()
            .useExpiredDataIfLoaderNotAvailable(true)
            .persistence(cacheDir)
            .using(Providers.class);

Android considerations

To build an instance of the interface used as provides by RxCache, you need to supply a reference to a file system. On Android, you can get the File reference calling getFilesDir() from the Android Application class.

Also, it is recommended to use this Android Application class to provide a unique instance of RxCache for the entire life cycle of your application.

In order execute the Observable on a new thread, and emit results through onNext on the main UI thread, you should use the built in methods provided by RxAndroid.

Check the Android example

Retrofit

RxCache is the perfect match for Retrofit to create a repository of auto-managed-caching data pointing to endpoints. You can check an example of RxCache and Retrofit working together.

Internals

RxCache serves the data from one of its three layers:

  • A memory layer -> Powered by Apache ReferenceMap.
  • A persisting layer -> RxCache uses internally Jolyglot for serialize and deserialize objects.
  • A loader layer (the observable supplied by the client library)

The policy is very simple:

  • If the data requested is in memory, and It has not been expired, get it from memory.
  • Else if the data requested is in persistence layer, and It has not been expired, get it from persistence.
  • Else get it from the loader layer.

Proguard

Proguard users MUST add the two given lines to their proguard configuration file and MUST use the @ProviderKey annotation method for every method that is being used as provider. Without the @ProviderKey annotation the method name will be used instead which can lead to providers that use the same name, see issue #96 for detailed information.

-dontwarn io.rx_cache2.internal.**
-keepclassmembers enum io.rx_cache2.Source { *; }
-keepclassmembernames class * { @io.rx_cache2.* <methods>; }

Author

Víctor Albertos

RxCache Swift version:

RxCache: Reactive caching library for Swift.

Another author's libraries using RxJava:

  • Mockery: Android and Java library for mocking and testing networking layers with built-in support for Retrofit.
  • RxActivityResult: A reactive-tiny-badass-vindictive library to break with the OnActivityResult implementation as it breaks the observables chain.
  • RxFcm: RxJava extension for Android Firebase Cloud Messaging (aka fcm).
  • RxSocialConnect: OAuth RxJava extension for Android.

rxcache's People

Contributors

alextrotsenko avatar daemontus avatar hick209 avatar jessyancoding avatar kibao avatar liaohuqiu avatar miguelbcr avatar paulwoitaschek avatar pavelsynek avatar readmecritic avatar rolf-smit avatar suki-huang avatar victoralbertos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rxcache's Issues

Question: How would one pre cache items?

Say I have an api that gets entities by id and a list of all entities.

I cache each entity by id, but when the application starts I would like to get all entities and cache each one by their id, thus when a get by id is called if the item has been pre cached then it is returned from cache, else it is loaded from the api by id.

Thanks!

Support for rx.Single

Title says it. It would be great to have support for singles (as all my api calls are Singles).

Use generic results in ClassCastException

i use retrofit + rxjava + rxcache in my demo,and the response json data format is

{
 "code": 200,
 "data": {}
}

so, i define a BaseResponse.class

public class BaseResponse<T> {
    public int code;
    public T datas;
}

Observable<BaseResponse<HomeDatasObj>> getHomeData();

but an error has occurred,java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to HomeDatasObj,I don't know how to solve this question.

RxCache dependency returns an apk archive

Hi Victor,

First let me say, thank you for sharing this library. I'm still just exploring, but so far it looks really cool.

I downloaded your sample project for android and configured it in Android Studio. Just a quick note that I had to change the double-quotes for calling your dependency in sample_date.build.gradle to single quotes or it wouldn't compile:

compile ('com.github.VictorAlbertos.RxCache:android:0.4.9') { exclude module: 'guava' }

Not a big deal at all, maybe that works fine in some environements...it just wouldn't work in mine.

The big issue I'm having right now is that the call for this dependency returns an APK instead of an AAR so I'm getting this error:

Warning:Dependency com.github.VictorAlbertos.RxCache:android:0.4.9 on project sample_android resolves to an APK archive which is not supported as a compilation dependency. File: /Users/foo/.gradle/caches/modules-2/files-2.1/com.github.VictorAlbertos.RxCache/android/0.4.9/a29a405c4d3c542571e9f062b7158916fecb2219/android-0.4.9.apk

Thanks,
Amanda

EvictDynamicKey was provided but not was provided any DynamicKey

Hey, After updating to RxJava 2 and use the appropriate RxCache version, I couldn't anymore make API requests,by using HttpLoggingInterceptor nothing happens when invoking "performGetQuiz" method..just an empty screen and logcat.

.debug D/Interactor$1$override: java.lang.IllegalArgumentException: getCachedQuestions EvictDynamicKey was provided but not was provided any DynamicKey

Code : https://gist.github.com/alouanemed/7aa9c2153fd80a31cfc74654743988a9

Providers return reference to objects but instead they should return copy of objects to preserve immutability

When I call to a provider and I retrieve an object from the cache (it can be a simple object, a list, ...) and I modify it, for instance, remove an item from the list, modify the object's properties, then the next time when I call to that provider, the provided object from the cache is the same object I've modified in my app.

So, I think the right behaviour should be that the providers return copy to objects, instead of return reference to objects. This way RxCache will be able to preserve immutability and stay sync with the persistence layer.

Url or path in DynamicKey cause file not found exception

If I specify some string with "/" symbol as DynamicKey value then RxCache generates own key based on this string and use it as part of path. But "/" symbol is not escaped or removed and it cause OnError when RxCache trying to create the file which directory doesn't exists.

Usage with Dagger 2.4

When I try to use RxCache in project that uses the latest version of Dagger (2.4 at this point of time), it crashes with java.lang.ClassNotFoundException: Didn't find class "dagger.internal.ScopedProvider" on path: DexPathList because Google introduced some breaking changes in 2.3 (everything works with 2.2).

It is easily reproducible by including Dagger 2.4 into a project that uses RxCache.

The easy solution is to update your Dagger version to 2.4, but new Dagger releases can potentially break it again. The ideal solution for me as user would be to remove Dagger dependency from the library, but I guess that's not an option.

Stop api calls if call returns empty list

If a retrofit api call returns with an empty list, is it possible to store the empty list in the cache and have RxCache load this empty list instead of making more api calls? Currently, for a given api call, the cache keeps making this call until it has data to store

The observable value must be a List, otherwise an error will be thrown.

I use @ Actionable, RxProviders provide the method is this:
@actionable
Observable<List> getChildRecommend(Observable<List> childEntity,
DynamicKey filterPage, EvictDynamicKey evictFilter);

Retrofit method is this:
@FormUrlEncoded
@post("/")
Observable<StatusEntity<List>> getChildRecommend(@fieldmap HashMap<String, String> params);

I call this:
CacheProvidersActionable.getChildRecommend(cacheProviders, new DynamicKey(makeKey(params)))
.addFirst(childEntity)
.toObservable()

Result The service does not see the server returning data?
I use the wrong way?

Add Proguard config to README

Proguard errors:

Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.CacheBuilder
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.CacheBuilder
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.CacheBuilder
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.CacheBuilder
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.cache.Cache
Warning: io.rx_cache.internal.GuavaMemory: can't find referenced class com.google.common.annotations.VisibleForTesting
Warning: io.rx_cache.internal.ProxyProviders: can't find referenced class com.google.common.annotations.VisibleForTesting
Warning: io.rx_cache.internal.Record: can't find referenced class com.google.common.annotations.VisibleForTesting
Warning: io.rx_cache.internal.cache.EvictExpirableRecordsPersistence: can't find referenced class com.google.common.annotations.VisibleForTesting
Warning: io.rx_cache.internal.cache.EvictRecord: can't find referenced class com.google.common.annotations.VisibleForTesting
Warning: io.rx_cache.internal.cache.TwoLayersCache: can't find referenced class com.google.common.annotations.VisibleForTesting
Warning: io.rx_cache.internal.cache.TwoLayersCache: can't find referenced class com.google.common.annotations.VisibleForTesting

Possible working solutions:

-dontwarn io.rx_cache.internal.GuavaMemory
-dontwarn io.rx_cache.internal.ProxyProviders
-dontwarn io.rx_cache.internal.Record
-dontwarn io.rx_cache.internal.cache.**

or

-dontwarn io.rx_cache.internal.**

I like second one more because it's future-proof.

Evict without doing get request?

Can you evict a certain observable from the cache without retrieving a new observable? With EvictProvider currently, if I pass in true, I evict and then retrieve a new observable immediately. Is there a way to just evict certain observables?

EDIT: Duplicate

Clear the cached data

There should be a way to clear all the cached data, from both disk and memory (with one single call).
For example, imagine a scenario where you have a user logged in with all his information cached either in disk and memory.
This user logs out an another user logs in in the same device, there might be some displayed information that actually belongs to the first user.

Of course you could evit every single cache entry you have, but this is very labourous. What if you have 20K individual cache entries?
So that's where a clearAll() method would come in handy.

Cannot clear memory cache

Hi,

So I am using this framework in an app that requires me to flush the cached memory data when a user logs out.

Is there an easy way of doing this?

The only way I have found so far is that I use the annotation Actionable and explicitly evictAll. But this poses a problem since the Actionable annotation can only be applied to results of List<>, leaving my other non-List<> data unable to be evicted.

Issue with `EvictDynamicKey was provided but not was provided any DynamicKey`

The first one, throws errors like this one:
EvictDynamicKey was provided but not was provided any DynamicKey

To be more specific, this is the stacktrace:

Fatal Exception: java.lang.IllegalArgumentException
matchesCacheInfo EvictDynamicKey was provided but not was provided any DynamicKey
 Raw
io.rx_cache.internal.ProxyTranslator.checkIntegrityConfiguration (ProxyTranslator.java:133)
io.rx_cache.internal.ProxyTranslator.processMethod (ProxyTranslator.java:45)
io.rx_cache.internal.ProxyProviders.invoke (ProxyProviders.java:78)
$Proxy1.getChatMessages (Unknown Source)
com.wwn.kickoff.data.repository.ChatDataRepository.getMergedMessages (ChatDataRepository.java:176)

It has a reference to matchesCacheInfo, but I'm not really calling this method.
Here's the code inside the method ChatDataRepository.getMergedMessages() with the line referenced by the stacktrace.

    private Observable<CacheData<ChatList>> getMergedMessages(final String username, final long userId, boolean refresh)
    {
        ...

        final Observable<ChatList> localCacheCall = cacheProvider.getChatMessages(Observable.just(new ChatList()), new DynamicKeyGroup(userId, KEY_CHAT_UNSENT_MESSAGES + "-" + username), new EvictDynamicKeyGroup(false));

        ...
    }

And here's the CacheProvider

public interface CacheProvider
{
    ...

    ///////////////////////////////
    /// Matches
    ///////////////////////////////

    Observable<MatchesList> getMatches(Observable<MatchesList> matches, DynamicKey key, EvictDynamicKey evict);
    Observable<CacheData.Info> matchesCacheInfo(Observable<CacheData.Info> cacheInfo, DynamicKey key, EvictDynamicKey evict);

    ...

    ///////////////////////////////
    /// Chat
    ///////////////////////////////

    Observable<ChatList> getChatMessages(Observable<ChatList> messages, DynamicKeyGroup key, EvictDynamicKey evict);
    Observable<CacheData.Info> chatCacheInfo(Observable<CacheData.Info> cacheInfo, DynamicKeyGroup key, EvictDynamicKeyGroup evict);

    @LifeCache(duration = 3, timeUnit = TimeUnit.DAYS)
    Observable<String> getChatMessageDraft(Observable<String> messages, DynamicKeyGroup key, EvictDynamicKeyGroup evict);

    ...
}

As you can see, it refers to the method matchesCacheInfo() in the stack trace, but the call itself has nothing to do with that method.

I've investigated it a fair bit, but still have no clue about what is happening.
Also, it's not a consistent thing, it happens occasionally, not every time.

Retrofit2 with RXCache

This doesn't seems to be working for me with retrofit

fot inserting :-
MyApplication.cacheProviders.getSignInToken(Observable.just(signInToken));

while fetching :-

 MyApplication.cacheProviders.getSignInToken(Observable.<SignInToken>just(null)).map(new Func1<SignInToken, String>() {
            @Override
            public String call(SignInToken signInToken) {
                Log.v(MyWorkoutsFragment.class.getName(),signInToken.getToken());
                return signInToken.getToken();
            }
        }).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                Toast.makeText(getActivity().getApplicationContext(),"Got Token",Toast.LENGTH_LONG).show();
            }
        });

What am i doing wrong ?

Misleading exception when cache directory does not exist

Hi, this is a minor thing, but I recently discovered that if you configure RxCache with a directory that does not exist (but can be created - so there are no access rights issues, someone just needs to call mkdirs on it), you are going to get the following exception:

io.rx_cache.RxCacheException: The Loader provided did not return any data and there is not data to load from the Cache getEpisodes
(Plus a very very long stack trace of course)

This I find a little dangerous, because it makes you start debugging the wrong parts of your code. :D Only if you go through the whole stack trace, on the bottom you can see that that it was caused by a file not found error. And even that isn't a very good hint, because if you don't know how the persistent cache works internally, you are going to assume that this just means there indeed isn't any data cached.

So I would propose to either:

  • Make sure the directory exists and is writeable right during the configuration phase
  • Or make the error handling a bit more flexible so that not everything looks like it was caused by an empty loader

(And I'll gladly make a pull request, just tell me which one seems better to you)

Evict without requesting new

Lets say I have 2 endpoints:
TrainingSummary and Trainings

Once I add a new training in the backend I want to evict the TrainingSummary for the day the training was uploaded. But I don't want to fetch new data instantly. Is that possible?

Too many dependencies

First of all, great work! A powerful library to apply together with Retrofit.

However, do you really need so many dependencies? As an Android Developer, I always work on minimizing method count. As far as I'm concerned, it's unnecessary to import Dagger and Guava. These will cause growth of method count.

Few questions about rx-cache.

I have few questions about RX-cache.

  1. Is it possible using RX-cache to filter data like fetch all live(live = 1) record.
  2. How can we sort our object on the basis of some fields.

If this is possible, then how can we achieve this. Any example will be helpful for me.

Thanks in advance.

Cache invalidation?

I.e, you've got smth from GET /api/smth/1 and then successfuly made PUT /api/smth/1 or DELETE /api/smth/1. Is it possible to force invalidate cache from GET method?

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap

i use retrofit + rxjava + rxcache in my project,and the response json data format is:

{"data":{},"status":200}

i define a BaseResponse.class ps : data is a object not list:

public class BaseResponse<T> { public int status; public T data; }

i define a cache interface method :
@LifeCache(duration = 20, timeUnit = TimeUnit.MINUTES) Observable<Reply<BaseResponse<UserBasicInfoResponse>>> loadUserBasicInfo(Observable<BaseResponse<UserBasicInfoResponse>> userBasicInfoResponseObservable , DynamicKey userId , EvictProvider evictProvider);

when racache load from memory it's ok,but raCache load from disk an error has occurred(java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap ),I don't know how to solve this question.

when i debug I find diskCache lose type "UserBasicInfoResponse", do you have any advice about it ?

thinks!

No multiple Cache Interfaces with same Methode names possible

Due to ProviderKey Generation it is not possible to have multiple cache interfaces with the same method names.

It would be great if the interface name gets added to the ProviderKey.

public interface UserCache {

  Observable<Reply<UserDto>> findOne(
      Observable<UserDto> oUser, DynamicKey userId, EvictDynamicKey update);

  Observable<Reply<List<UserDto>>> findAll(
      Observable<List<UserDto>> oUsers, EvictProvider update);

.... more methods
}
public interface RouteCache {

  Observable<Reply<RouteDto>> findOne(
      Observable<RouteDto> oRoute, DynamicKey id, EvictDynamicKey update);

  Observable<Reply<List<RouteDto>>> findAll(
      Observable<List<RouteDto>> oRoutes, EvictProvider evictProvider);

...more methods

NullPointerException on every start - Encryption disabled

First: Thx for this awesome library. 😄

I'm using a simple RXCache implementation with no encryption on Android with Retrofit2. Everything works fine. But on every start I get a NullPointerException, because the BuiltInEncryptor tries to generate a secret Key in generateSecretKey(String key). Due to no encryption the string key is null. Here is the head of the stackTrace:

06-29 14:04:11.647 7209-7235/? W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] java.lang.String.getBytes(java.lang.String)' on a null object reference
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.encrypt.BuiltInEncryptor.generateSecretKey(BuiltInEncryptor.java:81)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.encrypt.BuiltInEncryptor.initCiphers(BuiltInEncryptor.java:67)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.encrypt.BuiltInEncryptor.decrypt(BuiltInEncryptor.java:55)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.encrypt.FileEncryptor.decrypt(FileEncryptor.java:53)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.Disk.retrieveRecord(Disk.java:187)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.cache.EvictExpiredRecordsPersistence.startEvictingExpiredRecords(EvictExpiredRecordsPersistence.java:48)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.ProxyProviders$1.call(ProxyProviders.java:59)
06-29 14:04:11.647 7209-7235/? W/System.err:     at io.rx_cache.internal.ProxyProviders$1.call(ProxyProviders.java:57)

The root cause seems to be in EvictExpiredRecordsPersistence. The Method persistence.retrieveRecord(key, false, getEncryptKey.getKey()); returns null for a key and thats why he tries to get the record with encryption enabled.

Is this a Problem in RXCache or am I missing a configuration?

Thx for the help.

My Config:

public interface UserCache {

  Observable<Reply<UserDto>> usersFindOne(
      Observable<UserDto> oUser, DynamicKey userId, EvictDynamicKey update);

  Observable<Reply<List<UserDto>>> usersFindAll(
      Observable<List<UserDto>> oUsers, EvictProvider update);

.... more methods
}
public interface RouteCache {

  Observable<Reply<RouteDto>> routesFindOne(
      Observable<RouteDto> oRoute, DynamicKey id, EvictDynamicKey update);

  Observable<Reply<List<RouteDto>>> routesFindAll(
      Observable<List<RouteDto>> oRoutes, EvictProvider evictProvider);

...more methods
public class CacheFactory {

  private static <S> S createCache(Class<S> serviceClass, File cacheDir){
    return new RxCache.Builder()
        .useExpiredDataIfLoaderNotAvailable(true)
        .persistence(cacheDir, new JacksonSpeaker())
        .using(serviceClass);
  }

  public static UserCache getUserCache(File cacheDir){
    return createCache(UserCache.class, cacheDir);
  }

  public static RouteCache getRouteCache(File cacheDir){
    return createCache(RouteCache.class, cacheDir);
  }
}

Migrations

We need to create a simple mechanism for handle migrations between different deploy versions.

Issue with `EvictDynamicKey was provided but not was provided any DynamicKey`

The first one, throws errors like this one:
EvictDynamicKey was provided but not was provided any DynamicKey

To be more specific, this is the stacktrace:

Fatal Exception: java.lang.IllegalArgumentException
matchesCacheInfo EvictDynamicKey was provided but not was provided any DynamicKey
 Raw
io.rx_cache.internal.ProxyTranslator.checkIntegrityConfiguration (ProxyTranslator.java:133)
io.rx_cache.internal.ProxyTranslator.processMethod (ProxyTranslator.java:45)
io.rx_cache.internal.ProxyProviders.invoke (ProxyProviders.java:78)
$Proxy1.getChatMessages (Unknown Source)
com.wwn.kickoff.data.repository.ChatDataRepository.getMergedMessages (ChatDataRepository.java:176)

It has a reference to matchesCacheInfo, but I'm not really calling this method.
Here's the code inside the method ChatDataRepository.getMergedMessages() with the line referenced by the stacktrace.

    private Observable<CacheData<ChatList>> getMergedMessages(final String username, final long userId, boolean refresh)
    {
        ...

        final Observable<ChatList> localCacheCall = cacheProvider.getChatMessages(Observable.just(new ChatList()), keyForUnsentMessages(username, userId), new EvictDynamicKeyGroup(false));

        ...
    }

And here's the CacheProvider

public interface CacheProvider
{
    ...

    ///////////////////////////////
    /// Matches
    ///////////////////////////////

    Observable<MatchesList> getMatches(Observable<MatchesList> matches, DynamicKey key, EvictDynamicKey evict);
    Observable<CacheData.Info> matchesCacheInfo(Observable<CacheData.Info> cacheInfo, DynamicKey key, EvictDynamicKey evict);

    ...

    ///////////////////////////////
    /// Chat
    ///////////////////////////////

    Observable<ChatList> getChatMessages(Observable<ChatList> messages, DynamicKeyGroup key, EvictDynamicKey evict);
    Observable<CacheData.Info> chatCacheInfo(Observable<CacheData.Info> cacheInfo, DynamicKeyGroup key, EvictDynamicKeyGroup evict);

    @LifeCache(duration = 3, timeUnit = TimeUnit.DAYS)
    Observable<String> getChatMessageDraft(Observable<String> messages, DynamicKeyGroup key, EvictDynamicKeyGroup evict);

    ...
}

As you can see, it refers to the method matchesCacheInfo() in the stack trace, but the call itself has nothing to do with that method.

I've investigated it a bit but still have no clue about what is happening.
Also, it's not a consistent thing, it happens occasionally, not every time.

Breaks with data binding

When used along with Databinding and dagger, App doesn't compile and breaks the Data binding stuff.

Build Failed Proguard

i have activate proguard
and my project cant be build

i have added
-dontwarn io.rx_cache.** to my proguard-rules.pro but it seems still failed

here are log error from your project link
i have actived minifyEnabled:true and build using ./gradlew clean assembleRelease

Note: there were 9 unresolved dynamic references to classes or interfaces.
      You should check if you need to specify additional program jars.
      (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)
Note: there were 11 accesses to class members by means of introspection.
      You should consider explicitly keeping the mentioned class members
      (using '-keep' or '-keepclassmembers').
      (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclassmember)
Warning: there were 1615 unresolved references to classes or interfaces.
         You may need to add missing library jars or update their versions.
         If your code works fine without the missing classes, you can suppress
         the warnings with '-dontwarn' options.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)
Warning: there were 1 unresolved references to library class members.
         You probably need to update the library versions.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)
Warning: Exception while processing task java.io.IOException: Please correct the above warnings first.
:sample_android:transformClassesAndResourcesWithProguardForRelease FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':sample_android:transformClassesAndResourcesWithProguardForRelease'.
> java.io.IOException: Please correct the above warnings first.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 8.612 secs

have you trying build using proguard activate..? any suggestion proguard config for rxcache ? thanks

unable cache

io.rx_cache.internal.ProxyProviders$RxCacheException: The Loader provided did not return any data and there is not data to load from the Cache getNewsList

Survive Android configuration changes

Hello,
I'm just starting playing around with RxCache. Can it handle somehow configuration changes? What I mean by that is a typical use case:

  1. User starts an expensive network call.
  2. User rotates screen - request is still running in the background.
  3. After activity recreation it subscribes to ongoing call.

I've done some simple tests and it looks like on activity recreation the call is being reset.

Couldn't convert result of type rx.Observable to io.reactivex.Observable

Hey,

When updating to RxJava 2, I am getting this error :

Caused by: java.lang.ClassCastException: Couldn't convert result of type rx.Observable to io.reactivex.Observable

at this line of code (invoking the dataCached function), when retrieving data from the cache :

Observable apiObservable = ...
Observable observableCache = providers.getArticles(apiObservable, new EvictDynamicKey(isload)).map(
            new dataCached<List<Article>>());

Here is dataCached function :

    private  class dataCached<T> implements Function<Reply<T>, T> {
            @Override public T apply(Reply<T> httpResult) throws Exception  {
            return httpResult.getData();
        }

Anyway to solve this ? Thanks :)

Choose to not use Disk Cache

Hi,

So I'm about to use your framework but I see that using a Disk File for caching is mandatory. Can you make it NOT mandatory since I'm interested in your memory caching only.

This is useful with applications where we don't want to store cached data on the filesystem for security reasons.

Thanks!

Decoupled Gson dependency

Currently the library depends on Gson to serialise and deserialise objects. It is needed to abstract this feature into some interface and let the client to be who provides its custom vendor. For that matter, at least one built-in json convertor based on Gson it is needed to be implemented too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.