Oleksandr Katrych
04/14/2023, 4:55 PMViewModel
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.
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) }
)
}
Prateek Kumar
04/26/2023, 5:05 AMPrateek Kumar
04/26/2023, 5:05 AMPrateek Kumar
04/26/2023, 5:05 AM