Rx2Groups


Source link: https://github.com/rahulrj/Rx2Groups

This is the RxJava2 port of the RxGroups project developed by AirBnb. The branch rx-2.0 has the Rx2 changes. The changes have been done on master branch of RxGroups. The following documentation written for RxGroups by AirBnb applies to Rx2Groups as well. All the API and package names originally written by AirBnb remains as it is. I have transitioned all the RxJava APIs(including the unit tests) to RxJava2.

RxGroups

RxGroups lets you group RxJava Observables together in groups and tie them to your Android lifecycle. This is especially useful when used with Retrofit.

For simple scenarios you can probably just let the original request be cancelled and fire a new one. However it's easy to see how this becomes a problem in more complex situations.

Let's say your user is submitting a payment. You'll probably want to to guarantee that you can reattach to the same in-flight or completed request after rotating the screen or leaving the Activity and returning later.

RxGroups will also automatically prevent events from being delivered to your Activity or Fragment before onResume() and after onPause(). If that happens, they will be automatically cached in memory and delivered once the user returns to your screen. If they never return, the memory is then reclaimed automatically after onDestroy().

Usage

  1. Add a GroupLifecycleManager field to your Activity, Fragment, Dialog, etc. and call its respective lifecycle methods according to your own (eg.: onPause, onResume, onDestroy, etc.);
  2. Annotate your ResubscriptionObserver with @AutoResubscribe and use method resubscriptionTag() to tell RxGroups what tag it should use for reattaching your Observer to it Observable automatically.
  3. Before subscribing to your Observable, compose it with observableGroup.transform() to define a tag for that Observable;

Example

public class MyActivity extends Activity {

private static final String OBSERVABLE_TAG = "arbitrary_tag";
private TextView output;
private FloatingActionButton button;
private GroupLifecycleManager groupLifecycleManager;
private ObservableGroup observableGroup;
private Observable<Long> observable = Observable.interval(1, 1, TimeUnit.SECONDS);

 // The Observer field must be public, otherwise RxGroups can't access it
@AutoResubscribe public final ResubscriptionObserver<Long> observer = new ResubscriptionObserver<Long>() {

  @Override public void onCompleted() {

 Log.d(TAG, "onCompleted()");

  
}

@Override public void onError(Throwable e) {

 Log.e(TAG, "onError()", e);

  
}

@Override public void onNext(Long l) {

 output.setText(output.getText() + " " + l);

  
}

@Override public Object resubscriptionTag() {

 return OBSERVABLE_TAG;
  
}

}
;
 @Override protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  output = (TextView) findViewById(R.id.txt_output);

  button = (FloatingActionButton) findViewById(R.id.fab);

  SampleApplication application = (SampleApplication) getApplication();

  ObservableManager manager = application.observableManager();

  groupLifecycleManager = GroupLifecycleManager.onCreate(manager, savedInstanceState, this);

  observableGroup = groupLifecycleManager.group();

button.setOnClickListener(v -> observable

.compose(observableGroup.<Long>transform(OBSERVABLE_TAG))

.observeOn(AndroidSchedulers.mainThread())

.subscribe(observer));

}

 @Override protected void onSaveInstanceState(Bundle outState) {

  super.onSaveInstanceState(outState);

  groupLifecycleManager.onSaveInstanceState(outState);

}

 @Override protected void onResume() {

  super.onResume();

  groupLifecycleManager.onResume();

}

 @Override protected void onPause() {

  super.onPause();

  groupLifecycleManager.onPause();

}

 @Override protected void onDestroy() {

  super.onDestroy();

  groupLifecycleManager.onDestroy(this);

}
 
}

Optional: If you don't want to use a ResubscriptionObserverwith @AutoResubscribe just use a regular Observer anonymous class with a public method called resubscriptionTag(). Eg.:

@AutoResubscribe public final Observer<Long> observer = new Observer<Long>() {

  @Override public void onCompleted() {

  
}

@Override public void onError(Throwable e) {

  
}

@Override public void onNext(Long l) {

  
}

public Object resubscriptionTag() {

 return Arrays.asList("tag1", "tag2", "tag3");

  
}

}
;

If the method doesn't exist or is not public, RxGroups will throw a RuntimeException letting you know. You can use any Object tag for your Observer, including arrays and List, In that case, it will associate the Observer with all the tags in the collection, allowing you to share the same Observer with multiple Observables.

Download with Gradle

compile 'com.airbnb:rxgroups-android:0.3.5'

Check out the Sample app for more details and a complete example!

Snapshots of the development version are available in Sonatype's snapshots repository.

License

Copyright 2016 Airbnb, Inc.  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

A framework for building Mobile cross-platform UI.

A version info widget for Android with material style.

FogView is a android library that can show fog on any layout and the fog removes when user rubs it.

A custom Android TextView to display amounts of money in different formats.

A UI widget slider for android.

A simple way to authenticate with Google and Facebook using OAuth 2.0 in Android.

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