David Ibrahim
David Ibrahim

Reputation: 3227

How to scope a viewModel to a Dialog Composable Function which is not related to NavHost

I am using Android compose and view model and I have a ViewModel that is scoped to a single Composable function which is a bottom sheet view, which is inflated using BottomSheetScaffold and I inject the ViewModel inside the Composable function using viewModel but I have a problem that viewModel function returns the same viewModel instance created before when I open the bottom sheet again.

In other words how to scope the ViewModel to a Dialog Composable function which is not related to NavHost and backStack


@Composable
 fun ComposableExample(
) {
    val viewModel: ExampleViewModel= viewModel() // createdOnlyOnce and always returns old instance
}

Upvotes: 12

Views: 5206

Answers (2)

Sebas LG
Sebas LG

Reputation: 2195

This library scopes ViewModels or any other object to the lifecycle of a Composable using the call viewModelScoped (or rememberScoped)

https://github.com/sebaslogen/resaca

@Composable
fun ComposableExample(
) {
    val viewModel = viewModelScoped { ExampleViewModel() } // created Only Once and always returns old instance
}

PS: It also supports an optional key, in case you want to have multiple ViewModels of the same type with different data, like viewModelScoped(myId) { ExampleViewModel(myId) }

Upvotes: 1

ianhanniballake
ianhanniballake

Reputation: 199805

As per this issue, Compose does not offer any mechanism to scope ViewModels to an individual @Composable - any ViewModels you create outside of a NavHost's destination is scoped to the activity/fragment that contains your ComposeView/where you call setContent and, thus, lives for the entire lifetime of your Compose hierarchy - that's why you always get the same instance back.

Note that Navigation Compose has existing feature requests for supporting dialog destinations and for supporting BottomSheetScaffold, which would bring the same scoping of ViewModels and state to those types of destinations as well. You should star those issues to get updates and indicate your interest (which then helps prioritize that work).

Upvotes: 16

Related Questions