package com.example.viewmodelscope
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
class MainActivity : AppCompatActivity() {
private lateinit var mainActivityViewModel : MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var mainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
mainActivityViewModel.getUserData()
mainActivityViewModel.users.observe(this, Observer { myUsers ->
myUsers.forEach {
Log.i("MyTag", " name is ${it.name}")// it will run in the background
}
})
}
}
package com.example.viewmodelscope
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivityViewModel: ViewModel() {
private var userRepository = UserRepository()
var users : MutableLiveData<List<User>> = MutableLiveData()
fun getUserData() {
viewModelScope.launch {
var result: List<User>? = null
withContext(Dispatchers.IO) {
result = userRepository.getUsers()
}
users.value = result
}
}
}
package com.example.viewmodelscope
import kotlinx.coroutines.delay
class UserRepository {
suspend fun getUsers(): List<User> {
delay(8000)
val users: List<User> = listOf(
User(1, "Sam"),
User(2, "Taro"),
User(3, "Jane"),
User(4, "Amy")
)
return users
}
}package com.example.viewmodelscope
data class User(val id : Int , val name : String)
No comments:
Post a Comment