RxJava has become a standard in Android development. It's great until you have to deal with Android lifecycle. Normally you unsubscribe when view is destroyed and create new Observable after view is recreated. It's ok in most cases but sometimes there are actions, which cannot be done more than once i.e. HTTP Request which must be done once and Resposne must be received. In that cases Observables must be kept in place which lifecyle is different than destroyed view. This is where ObservableCache can be used. Library allows to cache Observable in global singleton map and retrieve same Observable after view is recreated. Internally library uses cache() for caching. Observables are automatically removed after onComplete.
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
Add the dependency
dependencies {
compile 'com.github.AleksanderMielczarek.ObservableCache:observable-cache-1:1.2.2'
}
public class MainActivity extends AppCompatActivity {
public static final String OBSERVABLE_CACHE_KEY_REQUEST = "observableRequest";
private ObservableCache observableCache;
private CompositeSubscription subscriptions;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
observableCache = LruObservableCache.getDefault();//get default singleton instance
subscriptions = new CompositeSubscription();
}
public void performObservableAction() {
Observable<String> observable = Observable.just("Test Action");
observableAction(observable
.compose(observableCache.cacheObservable(OBSERVABLE_CACHE_KEY_REQUEST)));//this line is responsible for caching observable
}
private void observableAction(Observable<String> testObservable) {
subscriptions.add(testObservable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s -> {/*do sth with result*/});
}
@Override
protected void onStart() {
super.onStart();
observableCache.<String>getObservable(OBSERVABLE_CACHE_KEY_REQUEST).ifPresent(this::observableAction);//retrieve observable from cache and perform action if observable exists
}
@Override
protected void onStop() {
super.onStop();
subscriptions.clear();
}
}
- caching Observable:
CacheableObservable<T> cachable = observableCache.cacheObservable(KEY);
- caching Single:
CacheableSingle<T> cachable = observableCache.cacheSingle(KEY);
- caching Completable:
CacheableCompletable<T> cachable = observableCache.cacheCompletable(KEY);
- retrieve Observable:
ObservableFromCache<T> fromCache = observableCache.<T>getObservable(KEY);
- retrieve Single:
SingleFromCache<T> fromCache = observableCache.<T>getSingle(KEY);
- retrieve Completable:
CompletableFromCache<T> fromCache = observableCache.<T>getCompletable(KEY);
- remove cached value:
boolean removed = observableCache.remove(KEY);
- get new instance of cache:
ObservableCache observableCache = LruObservableCache.newInstance();
- cache based on Map:
ObservableCache observableCache = MapObservableCache.newInstance();
Using ObservableCache requires from developer writing unique keys for cached Observables. This can be error prone and that's why additional layer can be used. Instead of directly using ObservableCache and manually manipulating keys, Observable Cache Service generate classes from declared interfaces which internally assures that all keys are unique.
Add it in your root build.gradle at the end of repositories:
Add to the dependencies
dependencies {
compile 'com.github.AleksanderMielczarek.ObservableCache:observable-cache-1-service:1.2.2'
annotationProcessor 'com.github.AleksanderMielczarek.ObservableCache:observable-cache-1-service-processor:1.2.2'
}
Previous example can be replaced with following implementation.
@ObservableCacheService
public interface CachedService {
CacheableObservable<String> testObservable();
ObservableFromCache<String> cachedTestObservable();
boolean removeTestObservable();
}
public class MainActivity extends AppCompatActivity {
private CachedService cachedService;
private CompositeSubscription subscriptions;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ObservableCache observableCache = LruObservableCache.getDefault();
ObservableCacheService observableCacheService = new ObservableCacheService(observableCache);
cachedService = observableCacheService.createObservableCacheService(CachedService.class);
subscriptions = new CompositeSubscription();
}
public void performObservableAction() {
Observable<String> observable = Observable.just("Test Action");
observableAction(observable
.compose(cachedService.testObservable()));//this line is responsible for caching observable
}
private void observableAction(Observable<String> testObservable) {
subscriptions.add(testObservable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s -> {/*do sth with result*/});
}
@Override
protected void onStart() {
super.onStart();
cachedService.cachedTestObservable().ifPresent(this::observableAction);//retrieve observable from cache and perform action if observable exists
}
@Override
protected void onStop() {
super.onStop();
subscriptions.clear();
}
}
Keys are generated based on method names:
- key value is based on method name that takes 0 arguments and returns CacheableObservable, CacheableSingle or CacheableCompletable
- method that retrieves value from cache takes 0 arguments and returns ObservableFromCache,
SingleFromCache or CompletableFromCache. Name of this method must be the same as method for
caching values + word 'cached':
- cache: 'testObservable()', retrieve: 'cachedTestObservable()'
- cache: 'testObservable()', retrieve: 'testCachedObservable()'
- cache: 'testObservable()', retrieve: 'testObservableCached()'
- method that removes value from cache takes 0 arguments and returns boolean.Name of this method
must be the same as method for caching values + word 'remove':
- cache: 'testObservable()', remove: 'removeTestObservable()'
- cache: 'testObservable()', remove: 'testRemoveObservable()'
- cache: 'testObservable()', remove: 'testObservableRemove()'
-keep class com.github.aleksandermielczarek.observablecache.service.ObservableCacheServiceCreatorImpl
RxJava 2 usage is very similar to RxJava 1.
New types:
- caching Flowable:
CacheableFlowable<T> cachable = observableCache.cacheFlowable(KEY);
- caching Maybe:
CacheableMaybe<T> cachable = observableCache.cacheMaybe(KEY);
- retrieve Flowable:
FlowableFromCache<T> fromCache = observableCache.<T>getFlowable(KEY);
- retrieve Maybe:
MaybeFromCache<T> fromCache = observableCache.<T>getMaybe(KEY);
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
Add the dependency
dependencies {
compile 'com.github.AleksanderMielczarek.ObservableCache:observable-cache-2:1.2.2'
}
Add it in your root build.gradle at the end of repositories:
Add to the dependencies
dependencies {
compile 'com.github.AleksanderMielczarek.ObservableCache:observable-cache-2-service:1.2.2'
annotationProcessor 'com.github.AleksanderMielczarek.ObservableCache:observable-cache-2-service-processor:1.2.2'
}
-keep class com.github.aleksandermielczarek.observablecache2.service.ObservableCacheServiceCreatorImpl
- make values from cache constructors public
- add static factory methods to values from cache
- simplify API
- change ifPresent method to void
- fix issue that does not remove Single and Maybe from cache
- add RxJava 2.x support
- rename RxJava 1.x modules
- add generator for caching interface
Copyright 2016 Aleksander Mielczarek
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.