RxLifecycle Documentation

repository·master·Indexed 19 days ago

https://github.com/zhihu/rxlifecycle

An Android library for automatically unsubscribing RxJava observable sequences when an Activity or Fragment is destroyed to prevent memory leaks. It uses a non-GUI fragment to monitor lifecycle events and provides the .compose(RxLifecycle.bind(...)) method to trigger unsubscription based on specified LifecycleEvents, such as DESTROY_VIEW.

Tokens
550
Snippets
2
Records
3
Agent score
18%

What's inside RxLifecycle

  1. How RxLifecycle manages lifecycle events

    master

    RxLifecycle uses the RxLifecycle.bind(context) method to attach to an Activity or Fragment. You specify which lifecycle event should trigger the unsubscription using disposeObservableWhen(LifecycleEvent).

    Commonly used events include LifecycleEvent.DESTROY_VIEW to clean up resources when the view is destroyed.

  2. Install RxLifecycle via JitPack

    master

    To integrate RxLifecycle into your Android project, first add the JitPack repository to your build.gradle file. Then, add the library dependencies to your dependencies block. You can choose between the standard library or the rxlifecycle-compact version if you want a smaller footprint.

    repositories {
        maven { url "https://jitpack.io" }
    }
    
    dependencies {
        compile 'com.github.nekocode.rxlifecycle:rxlifecycle:{lastest-version}'
        compile 'com.github.nekocode.rxlifecycle:rxlifecycle-compact:{lastest-version}' // Optional
    }
  3. Automatically unsubscribe Observables using RxLifecycle.bind()

    master

    RxLifecycle allows you to automatically unsubscribe from observable sequences when an Activity or Fragment is destroyed.

    Unlike other libraries, RxLifecycle actually performs the unsubscription, meaning downstream observers will no longer receive onComplete() or onError() once unsubscription occurs. It does not require you to inherit from specific base classes; instead, it inserts a non-GUI fragment to monitor lifecycle events.

    Important: To ensure that the downstream does not continue to emit items after the lifecycle event, you must place the .compose(RxLifecycle.bind(...)) call at the bottom of your observable chain.

    Observable.interval(0, 2, TimeUnit.SECONDS)
            // ...
            .compose(RxLifecycle.bind(this)
                    .<Long>disposeObservableWhen(LifecycleEvent.DESTROY_VIEW))
            .subscribe();