Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在类中调用视图模型_Android_Kotlin_Android Viewmodel - Fatal编程技术网

Android 在类中调用视图模型

Android 在类中调用视图模型,android,kotlin,android-viewmodel,Android,Kotlin,Android Viewmodel,我需要使用视图模型来像侦听器一样工作,但我的问题是如何在kotlin类中调用视图模型来观察目标属性 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

我需要使用视图模型来像侦听器一样工作,但我的问题是如何在kotlin类中调用视图模型来观察目标属性

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方法。试着这样做:

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 */ }
  }

}
class ExoplayerRapper{
private val_events=MutableLiveData(
val事件:LiveData
获取()=\u事件
初始化{
初始化图层()
value=“停止”
}
//示例法
私人娱乐暂停(){
_events.value=“暂停”
}
}
//然后外面
类SomeClass(玩家:ExoplayerRapper){
初始化{
player.events.observeforviever{event->/*处理事件*/}
}
}

是否要在
exoplayerRapper
类中初始化
LoginViewModel
?您的viewmodel应该绑定到生命周期所有者。您的包装器显然不是一个。是的,我想在exoplayerRapper类@AbuYousufI中初始化LoginViewModel,但解决方案是什么?我应该将我的类标记为生命周期所有者吗nk这是一个解决方案,但是如果我在一个视图模型中有我的所有观察者,并且我想在我的所有应用程序中使用它,该怎么办呢?它不推荐使用,我想避免使用不推荐使用的代码,但谢谢