MVP-RXAndroid


Source link: https://github.com/ahmedeltaher/MVP-RX-Android-Sample

What is ReactiveX ?

====== Reactive : Reactive programming is a programming paradigm oriented around data flows and the propagation of change. Reactive programming is programming with asynchronous data streams.

ReactiveX : - Is a library for composing asynchronous and event-based programs by using observable sequences. It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O. - Rx* library family is widely available for many languages and platforms ( .NET, Java , Scala, Clojure, JavaScript, Ruby, Python, C++, Objective-C/Cocoa, Groovy, etc).


What is RXAndroid ?

  • Extended version from RX-Java to Android .
  • RXAndroid provides many classes which facilities working with android , like - AndroidSchedulers for facilitating managing multi-threading. - AndroidObservable for facilitating dealing within the Android lifecycle. - ViewObservable & WidgetObservable for facilitating binding views , user clicks ... ect.

How RX concept works ?

  • An Observable performs some action, and publishes the result.
  • An Observer waits and watches the Observable, and reacts whenever the Observable publishes results.
  • There are three different changes that can occur on an Observable that the Observer reacts to. These are:
    • Publishing a value
    • Throwing an error
    • Completed publishing all values

When I can choose RXAndroid to do some behaviour ?

  • When we have concurrent tasks , like you would fetch data from Remote connections , database , any background processes .
  • When you would to handle stream of UI actions like : user scrolling , clicks , update UI upon some events .....ect .

What is the RXAndroid benefits?

RXAndroid will provide you to deal with below problems in one fell swoop:

  • No standard mechanism to recover from errors.
  • Lack of control over thread scheduling (unless you like to dig deep).
  • No obvious way to compose asynchronous operations.
  • No obvious and hassle-free way of attaching to Context.

Handle Retrofit with RXAndroid

  • Add RX to your gradle file

     compile 'io.reactivex:rxandroid:1.2.1'  compile 'io.reactivex:rxjava:1.1.6'  compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2' 
  • Replace Retrofit Call with Observable . From @GET("topstories/v2/home.json") Call<NewsModel> fetchNews(); to @GET("topstories/v2/home.json") Observable<Response<NewsModel>> fetchNews();

  • Create Observable 10. Inform your Observable to emit data in background thread with subscribeOn(Schedulers.io()) . 11. Inform your Observable to propagate its stream of data to Main Thread with observeOn(AndroidSchedulers.mainThread()) . 12. Register your subscriber to current Observable with subscribe(mSubscriber)

Observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mSubscriber);


 13. create subscriber

```
Subscriber mSubscriber=new Subscriber<Response<NewsModel>>() {

 @Override

 public void onCompleted() {
 //handle what should you do after Observable complete its emission , like dismiss dialog , build UI .

}

 @Override

 public void onError(Throwable e) {

  //Handle your error

}

 @Override

 public void onNext(Response<NewsModel> newsModelResponse) {

  // handle what should you do after receive each emission from observer , like update progress .... ect .

  
}

}
; 

Keep your code clean according to MVP

  • yes , RXAndroid is easy , powerful , but you should know in which MVP layer you will put it .
  • for observables which will emit data stream , it has to be in your data layer , and don't inform those observables any thing else like in which thread those will consume , cause it is another responsibility , and according to Single responsibility principle in SOLID (object-oriented design) , so don't break this concept by mixing every thing due to RXAndroid ease .


LICENSE

Copyright [2016] [Ahmed Eltaher]

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 simple and easy to use information view for Android.

An Android wrapper for the Rome2Rio API.

A port of Plaid's ReflowText that allows easily transitioning between sibling TextViews - no matter their size or style.

Kotlin delegates for Android Shared Preferences.

Add a cart icon with animated item counter to the Toolbar. You can increment the counter based on the number of unique items the user has in the shopping cart.

Another floating action button menu with expand/collapse behavior.

Menu resource example

The menu is structure from top to bottom, for example, the first one is the main button and the others will be the first option, second option and etc. The first item don't need to have a text because only the options have labels.

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