ObservableCache


Source link: https://github.com/AleksanderMielczarek/ObservableCache

ObservableCache

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.

RxJava 1.x

Observable Cache

Usage

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' 
}

Example

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();

  
}
 
}

More information

  • 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();

Observable Cache Service

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.

Usage

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' 
}

Example

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();

  
}
 
}

More information

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: 'test CachedObservable()'
    • cache: 'testObservable()', retrieve: 'testObservable Cached()'
  • 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: 'test RemoveObservable()'
    • cache: 'testObservable()', remove: 'testObservable Remove()'

ProGuard

-keep class com.github.aleksandermielczarek.observablecache.service.ObservableCacheServiceCreatorImpl 

RxJava 2.x

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);

Observable Cache

Usage

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' 
}

Observable Cache Service

Usage

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' 
}

ProGuard

-keep class com.github.aleksandermielczarek.observablecache2.service.ObservableCacheServiceCreatorImpl 

Changelog

1.2.2 (2017-07-19)

  • make values from cache constructors public

1.2.1 (2017-07-18)

  • add static factory methods to values from cache

1.2.0 (2017-03-06)

  • simplify API

1.1.2 (2017-03-05)

  • change ifPresent method to void

1.1.1 (2017-03-03)

  • fix issue that does not remove Single and Maybe from cache

1.1.0 (2017-02-10)

  • add RxJava 2.x support
  • rename RxJava 1.x modules

1.0.0 (2016-11-06)

  • add generator for caching interface

License

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. 

Resources

Confetti is a high-performance, easily-configurable particle system library that can animate any set of objects through space. You can specify your starting conditions and physical conditions (e.g. X and Y acceleration, boundaries, etc.), and let the confetti library take care of the rest.

Library to convert between RxJava 1.x and 2.x reactive types.

An A/B Testing Library for Android that makes writing simple tests simpler by using annotations.

CannyViewAnimator is an enhanced version of ViewAnimator. It allows to use Animators and Transitions to extend Visibility. The logic is taken from ViewAnimator of the Android SDK. ViewAnimator allows only one child to be visible at a time. Setting another child to be visible causes the previous child to become invisible. This switching occurs with animation.

Android HashTag library.

It's a cool way to show share widget.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes