copper-leaf / ballast

Opinionated Application State Management framework for Kotlin Multiplatform
https://copper-leaf.github.io/ballast/
BSD 3-Clause "New" or "Revised" License
144 stars 11 forks source link

Add a "ViewModel provider" to Navigation #58

Open cjbrooks12 opened 9 months ago

cjbrooks12 commented 9 months ago

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.

ubuntudroid commented 8 months ago

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.