Search code examples
androidkotlinandroid-viewmodel

Call View Model in Class


I need to Use the View model to work like a Listener but my Problem is how to call the view model in kotlin class to observe the target Attribute

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 
}

Solution

  • That does not seem to be a view, why not use just a simple 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 */ }
      }
    
    }