RxActivityResults


Source link: https://github.com/mohamad-amin/RxActivityResults

RxActivityResults

This library uses the power of RxJava to wrap an Observable android Activity#onActivityResult() method so you can easily request something from other activities and have the result right there in your observabale's subscribe() method.

Main Benifits

  • Don't Break The Chain: Prevents you to split your code between the permission request and the result handling. Currently without this library you have to request in one place and handle the result in Activity#onActivityResult().
  • Reactive: All what RX provides about transformation, filter, chaining...

If you have any issues or need more features, you can submit an issue in the issue tracker or make a pull request.

Importing

Add this line to your module's build.gradle file:

dependencies {

  compile 'com.mohamadamin.rxactivityresults:rxactivityresults:0.1' 
}

Usage

First you need to create an instance of RxActivityResults in your Activity:

RxActivityResults rxActivityResults;  @Override protected void onCreate(Bundle savedInstanceState) {

  ...
  rxActivityResults = new RxActivityResults(this);

  ... 
}

Then you can use this instance to start an activity for result and have it's result in your observer like this:

Intent intent = new Intent(this, LoginActivity.class);
 rxActivityResults.start(loginIntent)

  .subscribe(activityResult -> {

// Checking if the result's resultCode is Activity.RESULT_OK

if (activityResult.isOk()) {
                         Intent responseData = activityResult.getData();
                   

// Do some other things with the response data

  
}

  
}
);

 

Reactive Results

You can use RxActivityResults#composer(Intent intent) method to have an ObservableTransformer to chain your observables together and avoid from breaking the reactive chain:

( Note: we used RxBinding library to turn view clicks into an observable)

Disposable disposable = RxView.clicks(loginButton)

// Fire an intent when the user clicks on the button

.compose(rxActivityResults.composer(getLoginIntent()))

// Filter the activity results which their resultCode is Activity.RESULT_OK

.filter(activityResult -> activityResult.isOk())

// Extract the data intent of the activity result

.map(ActivityResult::getData)

.subscribe(intent -> {

  String firstName = intent.getStringExtra(LoginActivity.FIRST_NAME);

 String lastName = intent.getStringExtra(LoginActivity.LAST_NAME);

 String emailAddress = intent.getStringExtra(LoginActivity.EMAIL_ADDRESS);

  String result = getString(R.string.first_name) + ": " + firstName + "\n"

+ getString(R.string.last_name) + ": " + lastName + "\n"

+ getString(R.string.email_address) + ": " + emailAddress + "\n";

  loginInfoText.setText(result);

 
}
);
  disposables.add(disposable);

Chain Transformation

You can use RxActivityResults#ensureOkResult(Intent intent) method to have an ObservableTransformer to chain your observables together and avoid from breaking the reactive chain:

Disposable disposable = someAnotherChainOfObservables

// Fire an intent when the user clicks on the button

.compose(rxActivityResults.ensureOkResult(getIntent()))

.switchMap(okResult -> {

 if (okResult) {

  return someAnotherObservable();

 
}
 else {

  return Observable.error(new RuntimeException("Intent didn't return RESULT_OK"));

 
}

}
)

.flatMap(...)

...  disposables.add(disposable);

Demo

You can see a full demo of the library in the sample module.

Credits

This library was inspired by RxPermissions, so great thanks to @tbruyelle for his great contribution.

Licence

Copyright 2017 Mohamad Amin Mohamadi  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 helper class that extends SpannableStringBuilder and adds methods to easily mark the text with multiple spans.

Print it, cut it, give it to your designer!

Salut is a wrapper around the WiFi Direct service discovery API in Android. Before using Salut, you should at least skim over some of the documentation and recommended reading below.

NexusData is an object graph and persistence framework for Android. It allows for organizing and managing relational data and serializing it to SQLite or custom stores. The data can be accessed or modified using higher level objects representing entities and their relationships. NexusData manages all the objects in the persistence store, tracks changes, and maintains consistency in relationships.

NexusDialog is a library that allows you to dynamically generate forms in Android with little code. It's great for apps with many form-based UIs, since it reduces the boilerplate code to setup the view layout and tie things together in the Activity.

Plugin to navigate between events posted by EventBus.

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