GithubHelp home page GithubHelp logo

skydoves / viewmodel-lifecycle Goto Github PK

View Code? Open in Web Editor NEW
103.0 3.0 10.0 740 KB

๐ŸŒณ ViewModel Lifecycle allows you to track and observe Jetpack's ViewModel lifecycle changes.

License: Apache License 2.0

Kotlin 100.00%
android viewmodel jetpack-viewmodel observe coroutines lifecycle

viewmodel-lifecycle's Introduction

ViewModel Lifecycle


License API API Profile Android Weekly Dokka

๐ŸŒณ ViewModel Lifecycle allows you to track and observe Jetpack's ViewModel lifecycle changes.
Also, it supports useful extensions for RxKotlin/RxJava and Coroutines.

Including in your project

Maven Central

Gradle

Add the code below to your root build.gradle file (not your module build.gradle file):

allprojects {
    repositories {
        mavenCentral()
    }
}

Next, add the dependency below to your module's build.gradle file:

dependencies {
    implementation "com.github.skydoves:viewmodel-lifecycle:1.1.0"
}

SNAPSHOT

viewmodel-lifecycle
Snapshots of the current development version of ViewModel-Lifecycle are available, which track the latest versions.

repositories {
   maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}

Usage

ViewModel-Lifecycle allows you to observe two lifecycle changes: initialized and cleared.

ViewModelLifecycleOwner

ViewModelLifecycleOwner is a lifecycle owner for the Jetpack's ViewModel, which extends LifecycleOwner. It traces and provides lifecycle states for ViewModels. You can get the ViewModelLifecycleOwner from your ViewModel as the following:

class MyActivity : AppCompatActivity() {

  private val viewModel by viewModels<MyViewModel>()

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    val viewModelLifecycleOwner = viewModel.viewModelLifecycleOwner
...

Also, you can get it directly from your ViewModel as the following:

class MyViewModel : ViewModel() {

  val lifecycleOwner = viewModelLifecycleOwner
}

ViewModelLifecycleOwner for LiveData

You can also use it to observe your LiveData with the ViewModelLifecycleOwner depending on ViewModel's lifecycle. If the lifecycle moves to the cleared state, the observer will automatically be removed.

class MyViewModel : ViewModel() {

  private val liveData = MutableLiveData<String>()

  init {
    val lifecycleOwner = liveData.observe(viewModelLifecycleOwner) {
      // sometihng
    }
  }
}

Note: If you use ViewModelLifecycleOwner to observe your LiveData, observers will receive every event before the lifecycle moves to the cleared state. But you'll not receive further events by Activity recreations such as screen rotation. So make sure which lifecycleOwner is the best solution.

ViewModelLifecycle

ViewModelLifecycle is an implementation of the Lifecycle, which follows the ViewModel's lifecycle. ViewModelLifecycle handles multiple LifecycleObserver such as ViewModelLifecycleObserver to track ViewModel's lifecycle. ViewModelLifecycle belongs to ViewModelLifecycleOwner, and you can get it directly from the [ViewModelLifecycleOwner] as the following:

val viewModelLifecycle = viewModelLifecycleOwner.viewModelLifecycle

ViewModelLifecycle Observers

You can observe the lifecycle changes of the ViewModelLifecycle with addViewModelLifecycleObserver extension as the following:

viewModel.viewModelLifecycleOwner.addViewModelLifecycleObserver { viewModelState ->
  when (viewModelState) {
    ViewModelState.INITIALIZED -> // viewModel was initialized
    ViewModelState.CLEARED -> // viewModel was cleraed
  }
}

You can also observe the lifecycle changes of the ViewModelLifecycle with addObserver as the following:

viewModelLifecycleOwner.lifecycle.addObserver(
  object : DefaultViewModelLifecycleObserver {
    override fun onInitialized(viewModelLifecycleOwner: ViewModelLifecycleOwner) {
        // viewModel was initialized
    }

    override fun onCleared(viewModelLifecycleOwner: ViewModelLifecycleOwner) {
        // viewModel was cleraed
    }
  }
)

You can also implement your own custom lifecycle observer classes with DefaultViewModelLifecycleObserver and FullViewModelLifecycleObserver interfaces.

ViewModel Lifecycle for RxKotlin (RxJava)

Maven Central

ViewModel Lifecycle provides useful extensions for RxKotlin (RxJava).

Gradle

Add the dependency below to your module's build.gradle file:

dependencies {
    // RxKotlin3 (RxJava3)
    implementation "com.github.skydoves:viewmodel-lifecycle-rxkotlin3:$version"

    // RxKotlin2 (RxJava2)
    implementation "com.github.skydoves:viewmodel-lifecycle-rxkotlin2:$version"
}

AutoDisposable

With autoDisposable extension, you can create a Disposable delegate property which will call the dispose() function automatically when ViewModel will be cleared as the following:

class MyViewModel : ViewModel() {

  // dispose CompositeDisposable automatically when viewModel is getting cleared
  val compositeDisposable by autoDisposable(CompositeDisposable())
}

The autoDisposable extension creates a read-only property, which receives the Disposable interface as an inital value.

ViewModel Lifecycle for Coroutines

Maven Central

ViewModel-Lifecycle also supports Coroutines to track and observe ViewModel's lifecycle changes.

Gradle

Add the dependency below to your module's build.gradle file:

dependencies {
    implementation "com.github.skydoves:viewmodel-lifecycle-coroutines:$version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2"
}

ViewModelLifecycle Flow

You can observe lifecycle changes as a Flow with viewModelLifecycleFlow extension as the following:

class MyInteractor(
  private val viewModelLifecycleOwner: ViewModelLifecycleOwner
) : CoroutineScope {

  override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Main

  init {
    launch(coroutineContext) {
      viewModelLifecycleOwner.viewModelLifecycleFlow().collect { viewModelState ->
        when (viewModelState) {
          ViewModelState.INITIALIZED -> // ViewModel was initialized.
          ViewModelState.CLEARED -> {
            // ViewModel was cleared.
            coroutineContext.cancel() // cancel the custom scope.
          }
        }
      }
    }
  }
}

Make sure you cancel your custom CoroutineScope after observing the ViewModelState.CLEARED, and the viewModelLifecycleFlow extension must be launched on main thread.

Find this library useful? โค๏ธ

Support it by joining stargazers for this repository. โญ
And follow me for my next creations! ๐Ÿคฉ

License

Copyright 2022 skydoves (Jaewoong Eum)

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 L

viewmodel-lifecycle's People

Contributors

skydoves avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

viewmodel-lifecycle's Issues

Allow injecting closeable objects into ViewModel

https://android-review.googlesource.com/c/platform/frameworks/support/+/1984830

Will be updated with the new public API in the next release.


Allow injecting closeable objects into ViewModel

Rather than requiring developers manually override
onCleared() and close any open resources, provide
APIs to allow developers to add one or more
Closeable objects to the ViewModel that will be
closed when the ViewModel is cleared.

As a convenience, provide an additional constructor
for ViewModel that can directly takes one or more
Closeable objects, thus ensuring that injected
parameters can be directly added to the ViewModel.

TODO: RxJava/RxKotlin supports

Overview

Automatically call dispose() of the CompositeDisposable depending on ViewModel's lifecycle.

class MyViewModel: ViewModel() {
  // This will be automatically disposed of when ViewModel will be cleared.
  prival val compositeDisposable = AutoDisposeCompositeDisposable()
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.