1.創(chuàng)建 ViewModel
class FirstViewModel() : ViewModel() {
val userLiveData: LiveData<User>
get() = _userLiveData
private var _userLiveData = MutableLiveData<User>()
val userName: LiveData<String> = userLiveData.map {
it.name
}
init {
_userLiveData.value = User("Tom", 18)
}
fun getUser(userId: String): LiveData<User> {
return FirstRepository.getUser(userId)
}
fun add() {
// val count = _user.value ?: User("", 0)
// _user.value = User(_user.value.name ?: "", _user.value.age + 1)
}
fun clear() {
_userLiveData.value = User("", 0)
}
}
使用:
class FirstActivity : BaseActivity() {
private lateinit var viewModel: FirstViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
// ViewModel
// 常用
viewModel = ViewModelProvider(this).get(FirstViewModel::class.java)
// 給 ViewModel 傳參
// viewModel = ViewModelProvider(this, FirstViewModelFactory(100)).get(FirstViewModel::class.java)
viewModel.userLiveData.observe(this) {
mContentTv.text = it.toString()
}
}
}