android viewmodel code example
Example 1: android viewmodel dependency
dependencies {
def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"
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(){
.
.
.
.
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"
}