architecture-components-samples icon indicating copy to clipboard operation
architecture-components-samples copied to clipboard

Managing ViewModel lifetime with Navigation

Open pjcast opened this issue 7 years ago • 1 comments

Was trying to simply pass some data back to Fragment A that navigated to Fragment B, after calling popBackStack() in Fargment B. This proved challenging as it appears there is no built in way using the Navigation Component.

Looking around Google, appears that using a ViewModel was a recommended approach. And that does work... however, trying scope a ViewModel to a certain lifetime (lifetime of Fragment A, not Activity) proved daunting. This is because it appears darn near impossible (outside reflection) to find the ViewModelStore (aka Fragment A) instance from Fragment B while using Navigation Component.

Using a very simple/basic nav graph:

  • Home Screen Fragment -- Customer Detail Fragment (A) --- Customer Edit Fragment (B)

Getting Home screen fragment looked doable - but that is a root fragment, and scoping ViewModel to that is global. Getting the Customer Detail Fragment was a challenge... tried using childFragmentManager!!.getFragment(Bundle...) - which might work, but now way to know what the Key value is! since the keys change as fragments come/go.

Ended up using reflection - very bad - but could not find any other way, to get a Fragment which matched the passed in class name, then could use that to find a scoped ViewModel.

Sample code (note, using Koin, but shouldn't matter):

private val customerEditViewModel by sharedViewModel<CustomerEditViewModel>(from = {findRootFragmentByClassName(arguments!!.getString(SharedControllerName)!!)})

inline fun Fragment.findRootFragmentByClassName(className: String) : Fragment {
    // TODO: Find a better way! Navigation and scoped viewmodels is tricky
    val f = parentFragment!!.childFragmentManager::class.java.getDeclaredMethod("getActiveFragments")!!
    f.isAccessible = true

    val data = f.invoke(parentFragment!!.childFragmentManager) as List<Fragment>
    return data.first { it.javaClass.name == className}
}

Gotta be a better way that doesn't rely on internal SupportFragmentManager method...? Also tried using findFragmentById, but seems all Fragments in navigation graph have same id at runtime...

pjcast avatar Mar 07 '19 00:03 pjcast

This is going to be provided by the Navigation library itself as per this issue. Feel free to file future feature requests on the issue tracker, not here.

ianhanniballake avatar Mar 08 '19 23:03 ianhanniballake