Lifecycle scoping

Uber's https://github.com/uber/AutoDispose is a great library that automatically unsubscribe Observables as indicated by some scope, this allow us to bind the Observable with a Lifecycle(Fragment, Activity, view, etc...).

To use this feature all you need to do is to call .scoped() and pass in a LifecycleScopedProviderAutoDispose already comes with handy methods that we can use to build a LifecycleScopeProvider from a LifecycleOwner so all we need to do is to call

.scoped(AndroidLifecycleScopeProvider.from(this)) // Ex: Activity

and the returned Observable will bound to the Activity lifecycle.

// Builds an instance of Livebox using LiveboxBuilder class.
Livebox<UsersRes, Users> usersBox = new LiveboxBuilder<UsersRes, Users>()
                    .withKey("get_users")
                    .fetch(api::getUserList, UsersRes.class)
                    .addSource(Sources.MEMORY_LRU, ageValidator)
                    .addSource(Sources.DISK_PERSISTENT, persistentDiskValidator)
                    .addConverter(UsersRes.class, usersRes -> Optional.of(Users.fromUsersRes(usersRes)))
                    .retryOnFailure()
                    .build();
                   
// Using scoped feature, this uses Uber's autodispose                
usersBox.scoped(AndroidLifecycleScopeProvider.from(this))
                .subscribe(
                   users -> Log.d(TAG, "Users: " + users),
                   Throwable::printStackTrace
                 );

Last updated