RxLifecycle


Source link: https://github.com/florent37/RxLifecycle

RxLifecycle

Rx binding of stock Android Activities & Fragment Lifecycle, avoiding memory leak

This library allows one to automatically finish sequences based on Android lifecycle state, This capability is useful in Android, where incomplete subscriptions can cause memory leaks.

You don't need to extends Activity or Fragment

Compatible with all RxJava2 types : Single, Observable, Flowable, Maybe, Completable

mywebservice.searchUsers("florent")

 .observeOn(AndroidSchedulers.mainThread())

 .subscribeOn(Schedulers.io())

  //will dispose this call when the activity / fragment destroys

 .compose(disposeOnDestroy(this))

  //will wait until the screen is displayed

 .flatMap(users -> onlyIfResumedOrStarted(this, users))

  .subscribe(users -> {

  //display users with animation

 
}
);
 

dependencies {

compile 'com.github.florent37:rxlifecycle:(lastversion)'

compile "com.android.support:appcompat-v7:26.1.0"

 compile 'io.reactivex.rxjava2:rxjava:2.1.0'

}

Listen to activity / fragment lifecycle events

RxLifecycle.with((Fragment / Activity)this)

.onDestroy()

.subscribe(event ->

/*do what you had to do on view destroy*/

 );

  RxLifecycle.with(getLifeCycle())

.onResume()

.subscribe(event ->

/*do what you had to do on view resume*/

 );

Available events :

  • .onCreate()
  • .onStart()
  • .onResume()
  • .onPause()
  • .onStop()
  • .onDestroy()

Automatically Dispose Rx Observables

You can dispose an Rx operation when the activity state changes, for example

Using doOnSubscribe

mywebservice.searchUsers("florent")

 .doOnSubscribe(disposable -> RxLifecycle.with(this).disposeOnDestroyed<Long>(disposable)

 .subscribe(l ->

 ...

 
}
);
 

Shorter :

mywebservice.searchUsers("florent")

 .doOnSubscribe(disposable -> disposeOnDestroyed(this, disposable)

 .subscribe(l ->

 ...

 
}
);
 

With import static florent37.github.com.rxlifecycle.RxLifecycle.disposeOnDestroyed;

Or compose

mywebservice.searchUsers("florent")

 .compose(RxLifecycle.with(this).disposeOnDestroyed<Long>())

 .subscribe(l ->

 ...

 
}
);
 

Shorter :

mywebservice.searchUsers("florent")

 .compose(disposeOnDestroy(this))

 .subscribe(l ->

 ...

 
}
);
 

with import static florent37.github.com.rxlifecycle.RxLifecycle.disposeOnDestroy;

Availables : disposeOnStop, disposeOnPause, etc...

Wait until an Activity state

You can pause an Rx chain until it's not on an event, for example wait for activity to be resumed to perform an animation

mywebservice.searchUsers("florent")

//will pause

 .flatMap(l -> RxLifecycle.with(this).onlyIfResumedOrStarted(l))

//only if resumed

 .subscribe(l ->

...

 
}
);
 

Shorter :

mywebservice.searchUsers("florent")

//will pause

 .flatMap(l -> onlyIfResumedOrStarted(this, l))

//only if resumed

 .subscribe(l ->

 ...

 
}
);
 

with import static florent37.github.com.rxlifecycle.RxLifecycle.onlyIfResumedOrStarted;

Usage with MVP

You can bind easily your presenter with a lifecycle, example :

public abstract class AbstractPresenter<V extends AbstractPresenter.View> {

private WeakReference<V> viewReference;

@CallSuper
  public void bind(LifecycleOwner lifecycleOwner, V view) {

this.viewReference = new WeakReference<V>(view);

 RxLifecycle.with(lifecycleOwner)

  .onStart()

  .distinct() //once

  .subscribe(x -> start());

  
}

public abstract void start();

private interface View {

}
 
}

Credits

Author: Florent Champigny http://www.florentchampigny.com/

Blog : http://www.tutos-android-france.com/

License

Copyright 2017 Florent37, 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

Repository that contains android tutorial projects and sample applications.

A sample Android app using the MVP architecture, using:

  • Dagger2
  • mosby
  • retrofit2
  • RxJava

This is an Implementation of RecyclerView using Retrofit & Glide to Create a simple Movie List.

An Android library for panning a image horizontal and vertically.

A sample Android app using the MVP architecture.

Code Guide: How to create Snapchat-like stickers for 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