Android ViewModel (Kotlin)

Feb 27, 2019

ViewModel.

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

Dependencies.

dependencies {
    def lifecycle_version = "2.0.0"

    // ViewModel and LiveData
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    // alternatively - just ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    // alternatively - just LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"    

    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:$lifecycle_version"    
}

NOTE: One of my latest project seems to include androidx.lifecycle.* libraries without explicitly importing them, perhaps some google libraries included them as depedencies.

Activity

class MainActivity : AppCompatActivity() {    private lateinit var viewModel: MainViewModel    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)    }}

ViewModel

class MainViewModel : ViewModel() {    internal var lastActiveFragmentTag: String? = null}

NOTE: You might be interested to use Dagger2 with ViewModel.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.