voyager icon indicating copy to clipboard operation
voyager copied to clipboard

feat: added support to have navigator scoped ViewModel

Open programadorthi opened this issue 2 years ago • 7 comments

ISSUES SOLVED: #155 #168 and #210

Navigator scoped screen model was added on the #233

AndroidX ViewModel has support to scoped ViewModel here

So, we are supporting scoped ViewModel in Voyager too. How it works? Androidx has a function viewModel {} that use the local ViewModelStoreOwner so scoped ViewModel is supported by default. By default each Screen has your own ViewModelStoreOwner that doesn't support scoped and each screen will have a unique instance.

// ScreenA
val viewModel1 = viewModel { MyViewModel() }

// ScreenB
val viewModel2 = viewModel { MyViewModel() }

To have ViewModel scoped to a Navigator and share the same instance between screens do:

// ScreenA
val viewModel = rememberNavigatorViewModel<MyViewModel>()

// ScreenB
val viewModel = rememberNavigatorViewModel<MyViewModel>()

If you have a ViewModel scoped to Activity or Fragment do:

// ScreenA
val viewModel = viewModel(viewModelStoreOwner = activityOrFragmentViewModelStoreOwner) { SharedViewModel() }

@HiltViewModel has support now to use scoped ViewModel. To have or to get scoped ViewModel just provide to hilt function a ViewModelStoreOwner

programadorthi avatar Sep 23 '23 16:09 programadorthi

Any update on this PR?

osrl avatar Sep 27 '23 13:09 osrl

@programadorthi Is is possible for you to release this on your own fork? This is really a big challenge for me..

slickorange avatar Oct 04 '23 07:10 slickorange

Sorry guys. I can't. You will have to wait for owners review to check and avoid breaking changes.

programadorthi avatar Oct 06 '23 16:10 programadorthi

I'm really looking forward to this feature

renaudmathieu avatar Oct 11 '23 13:10 renaudmathieu

hi, are there any plans to merge this?

osrl avatar May 20 '24 11:05 osrl

@osrl we have a experimental support for it on the new Lifecycle KMP API.

DevSrSouza avatar Jun 04 '24 23:06 DevSrSouza