How to share view models between fragments using Google's GithubBrowserSample approach?

a 夏天 提交于 2021-01-27 12:08:01

问题


I am very new using Android architecture components, so I decided to base my application using GithubBrowserSample to achieve many of my use cases. But i have the problem that i don´t know what is the correct way to share viewmodels between fragments with this approach.

I want to share the view model because i have a fragment with a viewpager with 2 fragments that need to observe data of the parent fragment view model

I used this before to achieve it, based on google's documentation

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    model = activity?.run {
        ViewModelProviders.of(this)[SharedViewModel::class.java]
    } ?: throw Exception("Invalid Activity")
}

but with the lifecycle-extensions:2.2.0-alpha03 seems to be deprecated

In GithubBrowserSample they have something like this to create an instance of a view model, but with this it seems to be a different instance every time

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

private val userViewModel: UserViewModel by viewModels {
    viewModelFactory
}

And i don't know where to pass the activity scope or if I should pass it.

I tried something like this

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

private lateinit var myViewModel: MyViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    myViewModel = activity?.run {
        ViewModelProvider(this, viewModelFactory).get(MyViewModel::class.java)
    } ?: throw Exception("Invalid Activity")
}

but im getting

kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized

I hope you can help me, i'm a little lost with this, sorry if my english it´s not that good


回答1:


by viewModels() provides a ViewModel that is scoped to the individual Fragment. There's a separate by activityViewModels() that scopes the ViewModel to your Activity.

However, the direct replacement for ViewModelProviders.of(this) is simply ViewModelProvider(this) - you aren't required to switch to by viewModels() or by activityViewModels() when using lifecycle-extensions:2.2.0-alpha03



来源:https://stackoverflow.com/questions/57614060/how-to-share-view-models-between-fragments-using-googles-githubbrowsersample-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!