quver
04/21/2020, 2:35 PMscope
and view models
I found https://github.com/InsertKoinIO/koin/issues/440#issuecomment-489583308
this solution but still have questions. Could you please hellp me.
I see that recommended way is to use.
private val viewModel: TabViewModel by viewModel { parametersOf(lifecycleScope.id) }
but what if I need global VM in many fragments with different lifecycle
What is best practice for this case. how I should create scope and that it between fragments?
UPD: googled laso sharedViewModel
but it shared VM based on Actiity. and I need to share based on main fragment.aipok
04/21/2020, 2:58 PMsharedViewModel
instance.
I also prefer to attach VM scope to activity.quver
04/21/2020, 3:00 PMquver
04/21/2020, 3:11 PMsharedViewModel
activity is
owner: ViewModelStoreOwner
aipok
04/21/2020, 3:16 PMquver
04/21/2020, 3:41 PMaipok
04/21/2020, 4:03 PMquver
04/21/2020, 4:25 PMquver
04/21/2020, 4:37 PMval myScopeInstance = val myScopeInstance = koin.createScope("myScopeId",named(¨MY_SCOPE¨)).createScope("myScopeId",named(¨MY_SCOPE¨))
have and instance of koin in the Application and then ask for scope that I need from this variableaipok
04/21/2020, 6:35 PMquver
04/21/2020, 8:01 PMaipok
04/21/2020, 8:34 PMTabFragment
val viewModelModule = module {
scope(named<TabFragment>()) {
viewModel { TabViewModel() }
}
}
TabFragment will own VM like
private val viewModel: TabViewModel by lifecycleScope.viewModel(this)
And child fragments will get it like this
private lateinit var viewModel: TabViewModel
override fun onAttach(context: Context) {
super.onAttach(context)
viewModel = requireParentFragment().lifecycleScope.getViewModel(requireParentFragment())
}
As you can see below… each time while TabFragment is created, new instance of TabViewModel
is created and passed to child fragments
viewModel in TabFragment: com.troshchiy.testkoinscope.TabViewModel@dee6937
TabFragment. 169590436
viewModel in Fragment 1: com.troshchiy.testkoinscope.TabViewModel@dee6937
Fragment1. 245425006
viewModel in Fragment 2: com.troshchiy.testkoinscope.TabViewModel@dee6937
Fragment2. 142329978
ViewModel. init: 228
viewModel in TabFragment: com.troshchiy.testkoinscope.TabViewModel@cc6fdfd
TabFragment. 13331186
viewModel in Fragment 1: com.troshchiy.testkoinscope.TabViewModel@cc6fdfd
Fragment1. 115849630
viewModel in Fragment 2: com.troshchiy.testkoinscope.TabViewModel@cc6fdfd
Hope this helps 😄quver
05/05/2020, 12:33 PMviewModel = requireParentFragment().lifecycleScope.getViewModel(requireParentFragment())
works great!