android viewmodel code example

Example 1: android viewmodel dependency

dependencies {
    def lifecycle_version = "2.2.0"
    def arch_version = "2.1.0"

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    // Lifecycles only (without ViewModel or LiveData)
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

    // Saved state module for ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

    // Annotation processor
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    // optional - helpers for implementing LifecycleOwner in a Service
    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"

    // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

    // optional - ReactiveStreams support for LiveData
    implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"

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

Example 2: viewmodelscope android

package com.raj.coroutineall

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.delay

class ViewModelLiveDataScope: ViewModel() {


    private val _userId: MutableLiveData<Int> = MutableLiveData()
    val user = Transformations
        .switchMap(_userId) { _userId ->
        liveData(viewModelScope.coroutineContext +  IO ) {
            emit("database.loadUserById() / WebAPIcall()")
            delay(1000);
            emit("database.insertAll_into_another_DB()")
        }
    }



    fun setUserId(userId: Int){
        val update = userId
        if (_userId.value == update) {
            return
        }
        _userId.value = update
    }

}
-------------------------- Activity -------------------------------------
lateinit var viewModel: MainActivityViewModelOperation

oncreate(){
.
.
.
.
        //////////////////////  ViewModelLiveDataScope
        viewModel = ViewModelProvider(this).get(ViewModelLiveDataScope::class.java)
        viewModel.user.observe(this, Observer {
            Log.e("Return Value",it.toString())
            tex.text=it.toString()

        })
         viewModel.setUserId(1)
        //////////////////////
.
.
.
}

Example 3: how to use by viewModels()

compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }