在 Class 中调用视图模型
Call View Model in Class
我需要使用 View 模型像 Listener 一样工作,但我的问题是如何在 kotlin class 中调用视图模型来观察目标属性
class ExoPlayerWrapper(){
init {
initializePlayer()
// the next part of code need a lifecycle owner as Input to initilize the
// Provider and my class is not lifecycle owner
mLoginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
//mLoginViewModel.observe
}
我认为你缺少 ViewModelProviders.of(context) 方法。像这样试试:
viewModel = ViewModelProviders.of(this).get(CheckoutViewModel::class.java)
这似乎不是视图,为什么不使用简单的 LiveData?
class ExoPlayerWrapper {
private val _events = MutableLiveData<String>(
val events: LiveData<String>
get() = _events
init {
initializePlayer()
value = "stop"
}
// Example method
private fun notifyPause() {
_events.value = "pause"
}
}
// Then outside
class SomeClass(player: ExoPlayerWrapper) {
init {
player.events.observeForever { event -> /* handle event */ }
}
}
我需要使用 View 模型像 Listener 一样工作,但我的问题是如何在 kotlin class 中调用视图模型来观察目标属性
class ExoPlayerWrapper(){
init {
initializePlayer()
// the next part of code need a lifecycle owner as Input to initilize the
// Provider and my class is not lifecycle owner
mLoginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
//mLoginViewModel.observe
}
我认为你缺少 ViewModelProviders.of(context) 方法。像这样试试:
viewModel = ViewModelProviders.of(this).get(CheckoutViewModel::class.java)
这似乎不是视图,为什么不使用简单的 LiveData?
class ExoPlayerWrapper {
private val _events = MutableLiveData<String>(
val events: LiveData<String>
get() = _events
init {
initializePlayer()
value = "stop"
}
// Example method
private fun notifyPause() {
_events.value = "pause"
}
}
// Then outside
class SomeClass(player: ExoPlayerWrapper) {
init {
player.events.observeForever { event -> /* handle event */ }
}
}