ViewModel-Lifecycle - ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes

Overview

ViewModel Lifecycle


License API API Profile Dokka

🌳 ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes.

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.0.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 Jetpack 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 on 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 according to 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 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 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:1.0.0"
    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
You might also like...
Simple event library to communicate between Activity/Fragment and ViewModel

Setup dependencies { implementation "com.github.skgmn:viewmodelevent:1.1.0" } If you don't know how to access to GitHub Packges, please refer to

In this single activity app. i was trying to practice on ViewModel and Livedata

CalwithViewModel In this single activity app. i was trying to practice on ViewModel and Livedata Min Api Level : 19 Setup Requirements Android device

This is a practice app. An app that you can find random recipes and choose the ones you like.
This is a practice app. An app that you can find random recipes and choose the ones you like.

A food suggestion app like Tinder This is a practice app. In this app, you can find random recipes and choose the ones you like. This is main menu. Yo

A Simple Android library to get the number of words and give you the time it will take you to finish an article/story.

MinRead A Simple Android library to get the number of words and give you the time it will take you to finish an article/story. Prerequisite Androidx K

❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin)  architecture.
❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin) architecture.

MarvelHeroes MarvelHeroes is a demo application based on modern Android application tech-stacks and MVVM architecture. Fetching data from the network

🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, LiveData, Room, Repository, Koin) architecture.
🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, LiveData, Room, Repository, Koin) architecture.

DisneyMotions A demo Disney app using transformation motions based on MVVM architecture. The motion system is included in the 1.2.0-alpha05 released m

🔥采用 Kotlin 语言编写,专为新手入门准备的项目。单Activity多Fragment,MVVM,ViewModel + LiveData + Retrofit + 协程, ViewBinding等等。拒绝过度设计和封装,项目结构清晰,代码简洁优雅。
🔥采用 Kotlin 语言编写,专为新手入门准备的项目。单Activity多Fragment,MVVM,ViewModel + LiveData + Retrofit + 协程, ViewBinding等等。拒绝过度设计和封装,项目结构清晰,代码简洁优雅。

前言 学习Kotlin有一段时间了,想写一个项目总结收获,就有了这个可能是东半球最简洁的玩安卓客户端,在此感谢玩Android 的开放API。 简介 采用 Kotlin 语言编写,专为新手入门准备的项目。单Activity多Fragment,MVVM,ViewModel + LiveData + R

Starter code for Android Basics codelab - Store the data in a ViewModel

Unscramble App =================================== Starter code for Android Basics codelab - Store the data in a ViewModel Unscramble is a single pla

Exercício utilizando ViewModel e LiveData

Unscramble App Starter code for Android Basics codelab - Store the data in a ViewModel Unscramble is a single player game app that displays scrambled

Comments
  • Feature: viewmodel-lifecycle-rxkotlin2/rxkotlin3 modules

    Feature: viewmodel-lifecycle-rxkotlin2/rxkotlin3 modules

    Overview

    Introduce a new extension autoDisposable.. autoDisposable creates a [Disposable] read-only delegate property, which will call the Disposable.dispose() when the ViewModel is cleared.

    class SecondViewModel : ViewModel() {
    
      // The compositeDisposable will be called `dispose` automatically when the VeiwModel is cleared.
      val compositeDisposable by autoDisposable(CompositeDisposable())
    

    #2

    opened by skydoves 0
  • TODO: RxJava/RxKotlin supports

    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()
    }
    
    enhancement 
    opened by skydoves 0
  • Allow injecting closeable objects into ViewModel

    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.

    enhancement 
    opened by skydoves 1
Releases(1.1.0)
  • 1.1.0(Feb 3, 2022)

    🎉 Published a new version 1.1.0! 🎉

    Introduce

    Now it supports RxKotlin/RxJava for disposing of Disposable interfaces automatically when ViewModel will be cleared.

    class MyViewModel : ViewModel() {
    
      // dispose CompositeDisposable automatically when viewModel is getting cleared
      val compositeDisposable by autoDisposable(CompositeDisposable())
    }
    

    What's Changed

    • New feature: viewmodel-lifecycle-rxkotlin2/rxkotlin3 supports by @skydoves in https://github.com/skydoves/ViewModel-Lifecycle/pull/3
    • Implement traverseViewModel by @skydoves in https://github.com/skydoves/ViewModel-Lifecycle/pull/1

    Full Changelog: https://github.com/skydoves/ViewModel-Lifecycle/compare/1.0.0...1.0.1

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Feb 2, 2022)

Owner
Jaewoong Eum
Android Developer Advocate @GetStream 🥑 • Open Source Software Engineer ❤️ • Love coffee, music, magic tricks, and writing poems. Coffee Driven Development.
Jaewoong Eum
A fork of CloudStream-3, with additional features and changes

CloudStream-3XXX A fork of CloudStream-3, with additional features and changes. Features All features of CloudStream 3, corresponding to this commit h

Jace 137 Jan 9, 2023
New Relic Kotlin Instrumentation for Kotlin Coroutine. It successfully handles thread changes in suspend states.

new-relic-kotlin-coroutine New Relic Kotlin Instrumentation for Kotlin Coroutine. It successfully handles thread changes in suspend states. Usage 1- U

Mehmet Sezer 7 Nov 17, 2022
🛒 Mercado Libre App Clone using modern Android development with Hilt, Coroutines, Jetpack (Room, ViewModel), and Jetpack Compose based on MVVM architecture.

Meli Clone ?? Mercado Libre App Clone using modern Android development with Hilt, Coroutines, Jetpack (Room, ViewModel), and Jetpack Compose based on

Esteban Aragon 7 Sep 22, 2022
Explore-KiiT-App - An app to simplify the complicated website navigation and keep track of Attendance

KiiT Explore App "An app to simplify the complicated website navigation and keep

Ajay Khatri 17 Oct 12, 2022
Track RPG Playthrough Details

Shattered Ring Tracker This project is an RPG game tracker where the user can keep a journal of details about their game, including: NPCs Track the NP

Nathan Contino 1 Mar 16, 2022
Use Android Jetpack libraries, Android Architecture Components, ViewModel and LiveData to build this app.

Unscramble App Starter code for Android Basics codelab - Store the data in a ViewModel Unscramble is a single player game app that displays scrambled

Shaima Alghamdi 2 Aug 18, 2022
Allows you to use AWS KMS asymmetric keys as PGP/GPG keys.

KMS for PGP/GPG This tool allows you to use AWS KMS asymmetric keys as if they were PGP/GPG keys. (Only for signatures for now.) This can be useful if

Stojan Dimitrovski 8 Oct 21, 2022
A media player, currently only for Android, that allows you to play songs in background for free

Just Listen A music player currently only for android. It is using Audius public APIs to display and get the playlists/songs. Available on google play

null 68 Dec 27, 2022
KVision allows you to build modern web applications with the Kotlin language

KVision allows you to build modern web applications with the Kotlin language, without any use of HTML, CSS or JavaScript. It gives you a rich hierarchy of ready to use GUI components, which can be used as builder blocks for the application UI.

Robert Jaros 985 Jan 1, 2023
:cyclone: A Pokedex app using ViewModel, LiveData, Room and Navigation

Pokedex app built with Kotlin Download Go to the releases page to download the latest available apk. Screenshots Development Roadmap Kotlin LiveData N

Marcos Paulo Farias 1.4k Dec 28, 2022