Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a "ViewModel provider" to Navigation #58

Open
cjbrooks12 opened this issue Oct 8, 2023 · 1 comment
Open

Add a "ViewModel provider" to Navigation #58

cjbrooks12 opened this issue Oct 8, 2023 · 1 comment
Labels
hacktoberfest Help is wanted for Hacktoberfest

Comments

@cjbrooks12
Copy link
Member

While the current recommendation for Ballast Navigation is to keep ViewModels ephemeral and manage data shared between screens in a Repository, there are still some valid use cases for keeping a ViewModel instance alive and tied to the state of the Backstack.

For instance, a sub-flow that shares data among multiple steps in a mobile view. This data is technically persistent in that it is shared by multiple screens, but ephemeral in that the data should be cleared once the user exits or completes the flow. The current method would require managing that data globally in an application Repository, but then you need to keep track of when the user has left the flow to know when to clear it. This is a lot of bookkeeping that is easy to get wrong if done manually.

I think the best solution is to have an optional feature in the ballast-navigation artifact that scopes CoroutineScope instances to each entry in the Backstack. The scope is killed once the Backstack entry leaves the Backstack. Users then register ViewModels or other dependencies against that CoroutineScope. Notably, this API is not a full DI feature. It allows you to register a factory function to create some instance, and an API to get or create those instances. The CoroutineScope allows one to hook into cleanup events.

This basically reimplements the Android ViewModel provider functionality, but in KMP, and with less ceremony and no reflection.

@cjbrooks12 cjbrooks12 added the hacktoberfest Help is wanted for Hacktoberfest label Oct 8, 2023
@ubuntudroid
Copy link
Contributor

There also is state which doesn't really belong into a repository - mostly UI state, such as scroll state. For that a backstack-scoped view model can be quite handy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hacktoberfest Help is wanted for Hacktoberfest
Projects
None yet
Development

No branches or pull requests

2 participants