HiltSample icon indicating copy to clipboard operation
HiltSample copied to clipboard

想问一下,hilt 如何使用 application 的 ViewModelStore 生成 viewmodel

Open bytebubbles opened this issue 4 years ago • 1 comments

主要是想搞个全局的 viewmodel

bytebubbles avatar Apr 19 '21 07:04 bytebubbles

@HiltAndroidApp
class MyApplication:  Application(), ViewModelStoreOwner{

     private var mAppViewModelStore: ViewModelStore? = null
     override fun onCreate() {
       mAppViewModelStore = ViewModelStore()
      
     }

     override fun getViewModelStore(): ViewModelStore {
        return mAppViewModelStore!!
    }
}

class GlobalViewModel @ViewModelInject constructor(val serviceManager: ServiceManager): BaseViewModel() {
        
}

@AndroidEntryPoint
class MainActivity : MyBaseActivity() {
       private val globalShareModel: GlobalViewModel by lazy {
        ViewModelProvider(
            MyApplication.INSTANCE,
            ViewModelProvider.AndroidViewModelFactory.getInstance(MyApplication.INSTANCE)
        ).get(
            GlobalViewModel::class.java
        )
    }
}

这样的话,直接 java.lang.RuntimeException: Cannot create an instance of class com.xxx.GlobalViewModel

bytebubbles avatar Apr 19 '21 07:04 bytebubbles