I'm trying to figure out a way to hold the `ViewMo...
# compose-android
o
I'm trying to figure out a way to hold the
ViewModel
instance while
Dialog
is shown. One way of doing this is to create some
Map
which will hold instances of
ViewModelStoreOwner
and then clear it when
onDismissRequest
is called. Is there a better way of doing this? Edit: I know about https://github.com/sebaslogen/resaca which should work, but trying to find something simple.
Copy code
private val vmStoreOwnerMap = mutableMapOf<String, ViewModelStoreOwner>()

/**
 * Dialog which holds it's own [ViewModelStoreOwner], which gets cleared
 * after dialog is dismissed.
 */
@Composable
fun ScopedDialog(
    onDismissRequest: () -> Unit,
    properties: DialogProperties = DialogProperties(),
    content: @Composable (ViewModelStoreOwner) -> Unit,
) {
    val vmStoreOwnerKey: String = rememberSaveable { UUID.randomUUID().toString() }
    val vmStoreOwner = vmStoreOwnerMap.getOrPut(vmStoreOwnerKey) {
        object : ViewModelStoreOwner {
            override val viewModelStore: ViewModelStore = ViewModelStore()
        }
    }

    Dialog(
        onDismissRequest = {
            vmStoreOwnerMap[vmStoreOwnerKey]?.viewModelStore?.clear()
            vmStoreOwnerMap.remove(vmStoreOwnerKey)
            onDismissRequest()
        },
        properties = properties,
        content = { content(vmStoreOwner) }
    )
}
p
Untitled
I use this in my project, but it does not survive config changes
It supports passing key and works with hilt as well