oligazar
9/21/2018 - 5:58 AM

View Model

1#. ViewModelFactory

inline fun <VM : ViewModel> viewModelFactory(crossinline f: () -> VM) =
        object : ViewModelProvider.Factory {
            @Suppress("UNCHECKED_CAST")
            override fun <T : ViewModel> create(aClass: Class<T>):T = f() as T
        }
        
// Usage
private val viewModel by lazy {
  val factory = viewModelFactory { component.myViewModel() }
  ViewModelProviders.of(this, factory)
      .get(MyViewModel::class.java)
}

// More advanced example
inline fun <reified VM : ViewModel> Fragment.viewModelProvider(
        crossinline provider: () -> VM) = lazy {
    ViewModelProviders.of(this, object : ViewModelProvider.Factory {
        override fun <T1 : ViewModel> create(aClass: Class<T1>) =    
            provider() as T1
    }).get(VM::class.java)
}

// And cleaner one
inline fun <reified VM : ViewModel> Fragment.viewModelProvider(
    crossinline provider: () -> VM) = lazy {
    ViewModelProviders.of(this, viewModelFactory(provider)).get(VM::class.java)
}

// Usage
private val viewModel by viewModelProvider { 
    component.myViewModel() 
}