When using the handy new type-safe navigation in c...
# compose
c
When using the handy new type-safe navigation in compose... How should you access arguments from the SavedStateHandle in a ViewModel that backs a composable that is used in multiple destinations? For example, a form screen & view model that is used to create a new post, or edit an existing one. When editing, we would pass an existingId as an argument so that the ViewModel can initialise the form with existing data.
Copy code
// is there an optional version of the toRoute() ext fun?
data class NewPost
data class EditPost(val id: Int)

private val editPost : EditPost? = savedStateHandle.toRoute()
if (editPost != null) { initStateWithExistingData(editPost.id) }


// should a single destination type be used instead?
data class Post(val existingId: Int?)

private val post : Post = savedStateHandle.toRoute()
if (post.existingId != null) { initStateWithExistingData(post.existingId) }
s
Different destinations reusing the same VM might be a bit unorthodox. But you can do it the other way around, do the
toRoute()
on the graph, and as you call
by viewModel()
pass in there as a param the ID you want to be provided to the constructor of your VM. Then you won't be getting it from the SSH, but it's the same source of truth, the navigation parameters