<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ajinkya kalaskar on Medium]]></title>
        <description><![CDATA[Stories by Ajinkya kalaskar on Medium]]></description>
        <link>https://medium.com/@ajinkyakalaskarwork?source=rss-a08e17bfec1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QOavzI-ZkJmouy-p</url>
            <title>Stories by Ajinkya kalaskar on Medium</title>
            <link>https://medium.com/@ajinkyakalaskarwork?source=rss-a08e17bfec1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:59:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajinkyakalaskarwork/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Advanced Compose and ViewModel lifecycle management]]></title>
            <link>https://medium.com/@ajinkyakalaskarwork/advanced-compose-and-viewmodel-lifecycle-management-61ea62b846ee?source=rss-a08e17bfec1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ea62b846ee</guid>
            <dc:creator><![CDATA[Ajinkya kalaskar]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 16:32:49 GMT</pubDate>
            <atom:updated>2026-02-01T16:43:16.525Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering ViewModel Scoping in Kotlin Multiplatform:</h3><h3>The Scoped Store Registry Pattern for Dialogs and Bottom Sheets</h3><p>Stop Fighting ViewModel Lifecycles in Your Compose Dialogs</p><p>If you’ve ever built a complex dialog or bottom sheet in Jetpack Compose (or Compose Multiplatform), you’ve probably encountered this frustrating scenario:</p><p>You create a ViewModel inside your dialog using koinViewModel() or viewModel(), expecting it to have its own isolated state. But when you dismiss and reopen the dialog, the old state is still there. Or worse—multiple dialog instances share the same ViewModel, causing state conflicts and memory leaks.</p><p><strong>Why does this happen?</strong> Because ViewModels in Compose are scoped to their nearest ViewModelStoreOwner—typically a NavBackStackEntry, Activity, or Fragment. Dialogs and bottom sheets aren&#39;t navigation destinations; they&#39;re just composable functions. So they inherit the parent screen&#39;s ViewModel scope.</p><p>In this article, I’ll show you an elegant architectural pattern that solves this problem: <strong>The Scoped Store Registry Pattern</strong>. This approach gives each dialog its own isolated ViewModel lifecycle, automatically cleaning up resources when dismissed — all while maintaining the benefits of dependency injection with Koin.</p><h3>The Problem: Why Default ViewModel Scoping Fails for Transient UI</h3><p>Let’s start by understanding what goes wrong with the standard approach.</p><h3>The Naive Implementation</h3><p>Here’s what most developers try first:</p><pre>@Composable<br>fun MyScreen() {<br>    var showDialog by remember { mutableStateOf(false) }<br><br>    if (showDialog) {<br>        Dialog(onDismissRequest = { showDialog = false }) {<br>            // ❌ This ViewModel is scoped to MyScreen, not the dialog!<br>            val dialogViewModel = koinViewModel&lt;DialogViewModel&gt;()<br>            DialogContent(viewModel = dialogViewModel)<br>        }<br>    }<br>}</pre><h3>What Actually Happens</h3><ol><li><strong>Shared State</strong>: The DialogViewModel is created once and reused every time the dialog opens</li><li><strong>Stale Data</strong>: Previous dialog sessions leave behind state that persists</li><li><strong>Memory Leaks</strong>: The ViewModel never gets cleared when the dialog dismisses</li><li><strong>Lifecycle Mismatch</strong>: The ViewModel lives as long as the parent screen, not the dialog</li></ol><h3>The Root Cause</h3><p>The issue stems from how Compose resolves ViewModelStoreOwner:</p><pre>// Inside koinViewModel() or viewModel()<br>val owner = LocalViewModelStoreOwner.current // ← This is the parent screen!</pre><p>Since dialogs don’t create their own ViewModelStoreOwner, they inherit the parent&#39;s. This is by design—Compose has no way to know that your dialog needs its own ViewModel scope.</p><h3>The Solution: Scoped Store Registry Pattern</h3><p>The solution involves creating a <strong>registry ViewModel</strong> that manages multiple ViewModelStore instances, each identified by a unique ID. Think of it as a &quot;ViewModel factory for ViewModels.&quot;</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxze4AQb-cGhHpw1fWXq9w.png" /></figure><h3>The Two-Part Implementation</h3><p>The pattern consists of two components:</p><ol><li>ScopedStoreRegistryViewModel: The registry that manages ViewModelStores</li><li>DialogSheetScopedViewModel: A composable wrapper that provides scoped ViewModels to dialogs</li></ol><h3>Implementation Deep Dive</h3><h3>Part 1: The Registry ViewModel</h3><p>This ViewModel acts as a centralized manager for all dialog/sheet ViewModelStores:</p><pre>package com.plcoding.core.presentation.utils<br><br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.ViewModelStore<br><br>class ScopedStoreRegistryViewModel : ViewModel() {<br><br>    // Map of unique IDs to ViewModelStores<br>    private val stores = mutableMapOf&lt;String, ViewModelStore&gt;()<br><br>    // Get existing store or create new one<br>    fun getOrCreate(id: String): ViewModelStore =<br>        stores.getOrPut(id) { ViewModelStore() }<br><br>    // Clear specific store when dialog dismisses<br>    fun clear(id: String) {<br>        stores.remove(id)?.clear() // Triggers onCleared() on all VMs<br>    }<br><br>    // Cleanup all stores when parent screen is destroyed<br>    override fun onCleared() {<br>        super.onCleared()<br>        stores.values.forEach { it.clear() }<br>        stores.clear()<br>    }<br>}</pre><p><strong>Key Design Decisions:</strong></p><ul><li>getOrPut(): Thread-safe lazy initialization ensures one store per ID</li><li>clear(id): Explicitly removes and clears a store, triggering onCleared() on its ViewModels</li><li>onCleared(): Safety net that cleans up all remaining stores when the parent screen dies</li></ul><h3>Part 2: The Scoped Composable Wrapper</h3><p>This composable provides the scoped ViewModelStoreOwner to dialog content:</p><pre>package com.plcoding.core.presentation.utils<br><br>import androidx.compose.runtime.*<br>import androidx.lifecycle.ViewModelStore<br>import androidx.lifecycle.ViewModelStoreOwner<br>import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner<br>import org.koin.compose.viewmodel.koinViewModel<br>import kotlin.uuid.ExperimentalUuidApi<br>import kotlin.uuid.Uuid<br><br>@OptIn(ExperimentalUuidApi::class)<br>@Composable<br>fun DialogSheetScopedViewModel(<br>    visible: Boolean,<br>    scopeId: String = rememberSaveable { Uuid.random().toString() },<br>    content: @Composable () -&gt; Unit<br>) {<br>    // Get the parent screen&#39;s ViewModelStoreOwner<br>    val parentOwner = LocalViewModelStoreOwner.current<br>        ?: throw IllegalStateException(&quot;No parent owner found&quot;)<br><br>    // Get the registry ViewModel (scoped to parent)<br>    val registry = koinViewModel&lt;ScopedStoreRegistryViewModel&gt;(<br>        viewModelStoreOwner = parentOwner<br>    )<br><br>    // Track the dialog&#39;s ViewModelStoreOwner<br>    var owner by remember { mutableStateOf&lt;ViewModelStoreOwner?&gt;(null) }<br><br>    // Manage lifecycle based on visibility<br>    LaunchedEffect(visible, scopeId) {<br>        if (visible &amp;&amp; owner == null) {<br>            // Dialog opened: create scoped owner<br>            owner = object : ViewModelStoreOwner {<br>                override val viewModelStore: ViewModelStore<br>                    get() = registry.getOrCreate(scopeId)<br>            }<br>        } else if (!visible &amp;&amp; owner != null) {<br>            // Dialog dismissed: clear the store<br>            registry.clear(scopeId)<br>            owner = null<br>        }<br>    }<br><br>    // Provide the scoped owner to dialog content<br>    owner?.let { dialogOwner -&gt;<br>        CompositionLocalProvider(LocalViewModelStoreOwner provides dialogOwner) {<br>            content()<br>        }<br>    }<br>}</pre><p><strong>How It Works:</strong></p><ol><li><strong>Parent Owner Retrieval</strong>: Gets the parent screen’s ViewModelStoreOwner</li><li><strong>Registry Access</strong>: Retrieves the ScopedStoreRegistryViewModel from the parent scope</li><li><strong>Unique ID Generation</strong>: Creates a UUID that survives configuration changes via rememberSaveable</li><li><strong>Lifecycle Management</strong>: Uses LaunchedEffect to react to visibility changes</li><li><strong>Custom Owner Creation</strong>: Wraps the registry’s ViewModelStore in a ViewModelStoreOwner</li><li><strong>Composition Local Override</strong>: Provides the scoped owner to all child composables</li></ol><h3>Lifecycle Flow: From Creation to Cleanup</h3><p>Let’s trace the complete lifecycle of a dialog ViewModel:</p><h3>1. Dialog Opens (visible = true)</h3><p>User Action: showDialog = true<br> ↓<br>LaunchedEffect triggers (visible changed)<br> ↓<br>registry.getOrCreate(scopeId) creates new ViewModelStore<br> ↓<br>Custom ViewModelStoreOwner wraps the store<br> ↓<br>CompositionLocalProvider overrides LocalViewModelStoreOwner<br> ↓<br>Dialog content renders<br> ↓<br>koinViewModel&lt;DialogViewModel&gt;() uses scoped owner<br> ↓<br>DialogViewModel created in isolated store</p><h3>2. Dialog Dismisses (visible = false)</h3><p>User Action: showDialog = false<br> ↓<br>LaunchedEffect triggers (visible changed)<br> ↓<br>registry.clear(scopeId) called<br> ↓<br>ViewModelStore.clear() invoked<br> ↓<br>DialogViewModel.onCleared() called<br> ↓<br>Resources cleaned up (coroutines cancelled, etc.)<br> ↓<br>Store removed from registry<br> ↓<br>owner set to null<br> ↓<br>Dialog content removed from composition</p><h3>3. Parent Screen Destroyed</h3><p>Navigation away or Activity finish<br> ↓<br>ScopedStoreRegistryViewModel.onCleared() called<br> ↓<br>All remaining stores cleared<br> ↓<br>All dialog ViewModels receive onCleared()<br> ↓<br>Complete cleanup (safety net for unclosed dialogs)</p><h3>Real-World Use Cases</h3><h3>Use Case 1: Complex Form Dialog</h3><p>Imagine a “Create Post” dialog with validation, image upload, and API calls:</p><pre>@Composable<br>fun CreatePostDialog(<br>    visible: Boolean,<br>    onDismiss: () -&gt; Unit<br>) {<br>    if (visible) {<br>        DialogSheetScopedViewModel(visible = visible) {<br>            // ✅ This ViewModel is scoped to the dialog!<br>            val viewModel = koinViewModel&lt;CreatePostViewModel&gt;()<br>            val state by viewModel.state.collectAsStateWithLifecycle()<br><br>            Dialog(onDismissRequest = onDismiss) {<br>                CreatePostContent(<br>                    state = state,<br>                    onAction = viewModel::onAction<br>                )<br>            }<br>        }<br>    }<br>}</pre><p><strong>Benefits:</strong></p><ul><li>State resets every time the dialog opens</li><li>Image uploads are cancelled if the dialog is dismissed</li><li>No memory leaks from lingering coroutines</li></ul><h3>Use Case 2: Adaptive Bottom Sheet (Mobile) / Dialog (Tablet)</h3><pre>@Composable<br>fun UserProfileSheet(<br>    visible: Boolean,<br>    userId: String,<br>    onDismiss: () -&gt; Unit<br>) {<br>    if (visible) {<br>        DialogSheetScopedViewModel(visible = visible) {<br>            val viewModel = koinViewModel&lt;UserProfileViewModel&gt;()<br><br>            // Adaptive UI based on device<br>            ChirpAdaptiveDialogSheetLayout(onDismiss = onDismiss) {<br>                UserProfileContent(viewModel = viewModel)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Benefits:</strong></p><ul><li>Same ViewModel scoping works for both dialogs and bottom sheets</li><li>Consistent lifecycle management across device types</li><li>Clean separation of concerns</li></ul><h3>Use Case 3: Multi-Step Wizard in a Modal</h3><pre>@Composable<br>fun OnboardingWizardDialog(<br>    visible: Boolean,<br>    onComplete: () -&gt; Unit,<br>    onDismiss: () -&gt; Unit<br>) {<br>    if (visible) {<br>        DialogSheetScopedViewModel(visible = visible) {<br>            val wizardViewModel = koinViewModel&lt;OnboardingWizardViewModel&gt;()<br>            val currentStep by wizardViewModel.currentStep.collectAsStateWithLifecycle()<br><br>            Dialog(onDismissRequest = onDismiss) {<br>                when (currentStep) {<br>                    1 -&gt; WelcomeStep(onNext = wizardViewModel::nextStep)<br>                    2 -&gt; ProfileSetupStep(onNext = wizardViewModel::nextStep)<br>                    3 -&gt; PreferencesStep(onComplete = {<br>                        wizardViewModel.complete()<br>                        onComplete()<br>                    })<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Benefits:</strong></p><ul><li>Wizard state is isolated to the dialog session</li><li>Navigation between steps is managed by the scoped ViewModel</li><li>Dismissing the wizard properly cleans up all state</li></ul><h3>Step-by-Step Implementation Guide</h3><h3>Step 1: Add the Registry ViewModel to Your DI Module</h3><p>If you’re using Koin :</p><pre>// In your core presentation module<br>val corePresentationModule = module {<br>    viewModelOf(::ScopedStoreRegistryViewModel)<br>}</pre><h3>Step 2: Create Your Dialog ViewModel</h3><pre>class CreatePostViewModel(<br>    private val postRepository: PostRepository<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(CreatePostState())<br>    val state = _state.asStateFlow()<br><br>    fun onAction(action: CreatePostAction) {<br>        when (action) {<br>            is CreatePostAction.Submit -&gt; submitPost()<br>            is CreatePostAction.UploadImage -&gt; uploadImage(action.uri)<br>        }<br>    }<br><br>    private fun submitPost() {<br>        viewModelScope.launch {<br>            // API call to create post<br>        }<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        // Cleanup: cancel uploads, clear temp files, etc.<br>        println(&quot;CreatePostViewModel cleared - resources cleaned up&quot;)<br>    }<br>}</pre><h3>Step 3: Register Your Dialog ViewModel in DI</h3><pre>val featureModule = module {<br>    viewModelOf(::CreatePostViewModel)<br>}</pre><h3>Step 4: Use the Scoped Wrapper in Your UI</h3><pre>@Composable<br>fun MyScreen() {<br>    var showCreatePostDialog by remember { mutableStateOf(false) }<br><br>    Scaffold(<br>        floatingActionButton = {<br>            FloatingActionButton(onClick = { showCreatePostDialog = true }) {<br>                Icon(Icons.Default.Add, contentDescription = &quot;Create Post&quot;)<br>            }<br>        }<br>    ) {<br>        // Screen content<br>    }<br><br>    // Dialog with scoped ViewModel<br>    if (showCreatePostDialog) {<br>        DialogSheetScopedViewModel(visible = showCreatePostDialog) {<br>            val viewModel = koinViewModel&lt;CreatePostViewModel&gt;()<br>            val state by viewModel.state.collectAsStateWithLifecycle()<br><br>            Dialog(onDismissRequest = { showCreatePostDialog = false }) {<br>                CreatePostContent(<br>                    state = state,<br>                    onAction = viewModel::onAction,<br>                    onDismiss = { showCreatePostDialog = false }<br>                )<br>            }<br>        }<br>    }<br>}</pre><h3>Step 5: Verify Cleanup (Optional but Recommended)</h3><p>Add logging to your ViewModel’s onCleared() to verify it&#39;s being called:</p><pre>override fun onCleared() {<br>    super.onCleared()<br>    Log.d(&quot;CreatePostViewModel&quot;, &quot;ViewModel cleared - dialog dismissed&quot;)<br>}</pre><p>When you dismiss the dialog, you should see this log message immediately.</p><h3>Best Practices and When to Use This Pattern</h3><h3>✅ Use This Pattern When:</h3><ol><li><strong>Complex State Management</strong>: Your dialog has business logic, validation, or API calls</li><li><strong>Resource Management</strong>: You need to clean up resources (uploads, subscriptions) when dismissed</li><li><strong>Multiple Instances</strong>: You might show multiple dialogs simultaneously (e.g., nested dialogs)</li><li><strong>Adaptive UI</strong>: You switch between dialogs and bottom sheets based on device type</li><li><strong>Multi-Step Flows</strong>: Your dialog contains a wizard or multi-step process</li></ol><h3>❌ Don’t Use This Pattern When:</h3><ol><li><strong>Simple Alerts</strong>: For basic confirmation dialogs with no state</li><li><strong>Static Content</strong>: Dialogs that just display information without interaction</li><li><strong>Parent State is Sufficient</strong>: When the parent screen’s ViewModel can handle the dialog’s logic</li></ol><h3>Alternative Approaches</h3><p><strong>For Simple Dialogs:</strong></p><pre>// Just use local state - no ViewModel needed<br>var showDialog by remember { mutableStateOf(false) }<br><br>if (showDialog) {<br>    AlertDialog(<br>        onDismissRequest = { showDialog = false },<br>        title = { Text(&quot;Confirm&quot;) },<br>        text = { Text(&quot;Are you sure?&quot;) },<br>        confirmButton = { Button(onClick = { showDialog = false }) { Text(&quot;Yes&quot;) } }<br>    )<br>}</pre><p><strong>For Parent-Managed State:</strong></p><pre>// Use the parent screen&#39;s ViewModel<br>@Composable<br>fun MyScreen(viewModel: MyScreenViewModel = koinViewModel()) {<br>    val showDialog by viewModel.showDialog.collectAsStateWithLifecycle()<br><br>    if (showDialog) {<br>        Dialog(onDismissRequest = { viewModel.hideDialog() }) {<br>            // Use viewModel directly - it&#39;s already scoped to the screen<br>            DialogContent(onAction = viewModel::onDialogAction)<br>        }<br>    }<br>}</pre><h3>Common Pitfalls and Troubleshooting</h3><h4>Pitfall 1: Forgetting to Pass visible Parameter</h4><pre>// ❌ Wrong: visible is always true<br>DialogSheetScopedViewModel(visible = true) { ... }<br><br>// ✅ Correct: visible reflects actual state<br>DialogSheetScopedViewModel(visible = showDialog) { ... }</pre><h4>Pitfall 2: Not Wrapping the Entire Dialog</h4><pre>// ❌ Wrong: Wrapper inside Dialog<br>Dialog(onDismissRequest = onDismiss) {<br>    DialogSheetScopedViewModel(visible = visible) {<br>        // ViewModel won&#39;t be cleaned up properly<br>    }<br>}<br><br>// ✅ Correct: Wrapper outside Dialog<br>DialogSheetScopedViewModel(visible = visible) {<br>    Dialog(onDismissRequest = onDismiss) {<br>        // ViewModel lifecycle is properly managed<br>    }<br>}</pre><h4>Pitfall 3: Sharing scopeId Between Dialogs</h4><pre>// ❌ Wrong: Same scopeId for different dialogs<br>val sharedId = rememberSaveable { Uuid.random().toString() }<br><br>DialogSheetScopedViewModel(visible = showDialog1, scopeId = sharedId) { ... }<br>DialogSheetScopedViewModel(visible = showDialog2, scopeId = sharedId) { ... }<br><br>// ✅ Correct: Each dialog gets its own scopeId (default behavior)<br>DialogSheetScopedViewModel(visible = showDialog1) { ... }<br>DialogSheetScopedViewModel(visible = showDialog2) { ... }</pre><h3>Performance Considerations</h3><h3>Memory Footprint</h3><p>The ScopedStoreRegistryViewModel has minimal overhead:</p><ul><li>One registry ViewModel per screen (not per dialog)</li><li>Each dialog adds one ViewModelStore entry to the map</li><li>Stores are immediately cleared when dialogs dismiss</li></ul><h3>Thread Safety</h3><p>The implementation is thread-safe:</p><ul><li>getOrPut() is atomic in Kotlin&#39;s MutableMap</li><li>LaunchedEffect runs on the main thread</li><li>ViewModel lifecycle callbacks are guaranteed to run on the main thread</li></ul><h3>Configuration Changes</h3><p>The pattern handles configuration changes gracefully:</p><ul><li>rememberSaveable preserves the scopeId across rotations</li><li>The registry ViewModel survives configuration changes (scoped to parent)</li><li>Dialog state is preserved if the dialog remains visible during rotation</li></ul><h3>Testing Your Scoped ViewModels</h3><h4>Unit Testing the Dialog ViewModel</h4><pre>class CreatePostViewModelTest {<br><br>    @Test<br>    fun `when submit is clicked, post is created`() = runTest {<br>        // Arrange<br>        val mockRepository = mockk&lt;PostRepository&gt;()<br>        val viewModel = CreatePostViewModel(mockRepository)<br><br>        // Act<br>        viewModel.onAction(CreatePostAction.Submit(&quot;Test post&quot;))<br><br>        // Assert<br>        coVerify { mockRepository.createPost(any()) }<br>    }<br><br>    @Test<br>    fun `when ViewModel is cleared, resources are cleaned up`() {<br>        // Arrange<br>        val viewModel = CreatePostViewModel(mockRepository)<br><br>        // Act<br>        viewModel.onCleared() // Manually trigger cleanup<br><br>        // Assert<br>        // Verify cleanup logic (e.g., uploads cancelled)<br>    }<br>}</pre><h4>Integration Testing with Compose</h4><pre>@Test<br>fun `dialog ViewModel is cleared when dismissed`() {<br>    var showDialog by mutableStateOf(true)<br>    var viewModelCleared = false<br><br>    composeTestRule.setContent {<br>        if (showDialog) {<br>            DialogSheetScopedViewModel(visible = showDialog) {<br>                val viewModel = remember {<br>                    object : ViewModel() {<br>                        override fun onCleared() {<br>                            viewModelCleared = true<br>                        }<br>                    }<br>                }<br>                Dialog(onDismissRequest = { showDialog = false }) {<br>                    Text(&quot;Dialog content&quot;)<br>                }<br>            }<br>        }<br>    }<br><br>    // Dismiss dialog<br>    showDialog = false<br>    composeTestRule.waitForIdle()<br><br>    // Verify ViewModel was cleared<br>    assertTrue(viewModelCleared)<br>}</pre><h3>Kotlin Multiplatform Considerations</h3><p>This pattern works seamlessly across all KMP targets:</p><h3>Android</h3><ul><li>Uses standard ViewModel and ViewModelStore from AndroidX</li><li>Integrates with Activity/Fragment lifecycle</li><li>Supports process death and restoration</li></ul><h3>iOS</h3><ul><li>Uses the KMP-compatible ViewModel implementation</li><li>Works with SwiftUI interop</li><li>Handles app backgrounding correctly</li></ul><h3>Desktop (JVM)</h3><ul><li>Full support for Compose Desktop</li><li>Works with window lifecycle</li><li>Handles multi-window scenarios</li></ul><h3>Web (Wasm)</h3><ul><li>Compatible with Compose for Web</li><li>Manages browser tab lifecycle</li><li>Handles page navigation</li></ul><h3>Advanced Patterns</h3><h3>Nested Dialogs</h3><p>You can nest dialogs, each with their own scoped ViewModel:</p><pre>DialogSheetScopedViewModel(visible = showParentDialog) {<br>    val parentViewModel = koinViewModel&lt;ParentDialogViewModel&gt;()<br><br>    Dialog(onDismissRequest = { showParentDialog = false }) {<br>        ParentDialogContent()<br><br>        // Nested dialog with its own scoped ViewModel<br>        if (showChildDialog) {<br>            DialogSheetScopedViewModel(visible = showChildDialog) {<br>                val childViewModel = koinViewModel&lt;ChildDialogViewModel&gt;()<br>                Dialog(onDismissRequest = { showChildDialog = false }) {<br>                    ChildDialogContent()<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Shared State Between Dialog and Parent</h3><p>If you need to share some state between the dialog and parent screen:</p><pre>@Composable<br>fun MyScreen(screenViewModel: MyScreenViewModel = koinViewModel()) {<br>    var showDialog by remember { mutableStateOf(false) }<br><br>    if (showDialog) {<br>        DialogSheetScopedViewModel(visible = showDialog) {<br>            val dialogViewModel = koinViewModel&lt;DialogViewModel&gt;()<br><br>            // Pass parent ViewModel&#39;s data to dialog<br>            Dialog(onDismissRequest = { showDialog = false }) {<br>                DialogContent(<br>                    dialogViewModel = dialogViewModel,<br>                    sharedData = screenViewModel.sharedData // From parent<br>                )<br>            }<br>        }<br>    }<br>}</pre><h3>Custom Scope IDs for Persistence</h3><p>Use custom scope IDs to preserve dialog state across app restarts:</p><pre>DialogSheetScopedViewModel(<br>    visible = showDialog,<br>    scopeId = &quot;create_post_draft_${userId}&quot; // Persistent ID<br>) {<br>    val viewModel = koinViewModel&lt;CreatePostViewModel&gt;()<br>    // ViewModel can save/restore draft from persistent storage<br>}</pre><h3>Conclusion: Clean Architecture for Transient UI</h3><p>The Scoped Store Registry Pattern solves a fundamental problem in Compose: <strong>how to give transient UI components their own ViewModel lifecycle</strong>. By creating a registry that manages isolated ViewModelStore instances, we achieve:</p><h3>Key Benefits Recap</h3><p>✅ <strong>Proper Lifecycle Management</strong>: ViewModels are created when dialogs open and cleared when they dismiss</p><p>✅ <strong>Isolated State</strong>: Each dialog instance has its own independent state</p><p>✅ <strong>Automatic Cleanup</strong>: Resources are released immediately, preventing memory leaks</p><p>✅ <strong>Configuration Change Support</strong>: State survives rotations if the dialog remains visible</p><p>✅ <strong>Testability</strong>: Dialog ViewModels can be unit tested independently</p><p>✅ <strong>Scalability</strong>: Supports multiple simultaneous dialogs and nested dialogs</p><p>✅ <strong>KMP Compatible</strong>: Works across all Kotlin Multiplatform targets</p><h3>When to Use It</h3><p>This pattern shines when building:</p><ul><li>Complex forms in dialogs</li><li>Multi-step wizards</li><li>Adaptive UI (dialog/sheet based on device)</li><li>Dialogs with network operations</li><li>Any transient UI that needs business logic</li></ul><h3>The Bigger Picture</h3><p>This pattern demonstrates a key principle of clean architecture: <strong>matching component lifecycles to their responsibilities</strong>. Just as Activities, Fragments, and NavBackStackEntries have their own ViewModelStores, dialogs and bottom sheets deserve the same treatment when they contain complex logic.</p><p>By implementing this pattern in your Kotlin Multiplatform Compose app, you’re not just solving a technical problem — you’re establishing a consistent, maintainable architecture that scales with your application’s complexity.</p><h3>Next Steps</h3><ol><li><strong>Implement the pattern</strong> in your own project</li><li><strong>Add logging</strong> to onCleared() to verify proper cleanup</li><li><strong>Test with LeakCanary</strong> to confirm no memory leaks</li><li><strong>Share your experience</strong> in the comments below!</li></ol><h3>Let’s Connect</h3><p>If you found this pattern useful, please:</p><ul><li>👏 <strong>Clap</strong> for this article (up to 50 times!)</li><li>💬 <strong>Comment</strong> with your use cases or questions</li><li>🔗 <strong>Share</strong> with your team and the Android/KMP community</li><li>🔔 <strong>Follow me</strong> for more deep dives into Kotlin Multiplatform architecture</li></ul><p>Have you encountered ViewModel scoping issues in your Compose apps? How did you solve them? I’d love to hear your approaches in the comments!</p><p><strong><em>About the Author</em></strong><em>: This pattern was developed and refined while building a Kotlin Multiplatform messaging application. It’s been battle-tested across Android, iOS, and Desktop platforms.</em></p><blockquote>#KotlinMultiplatform #JetpackCompose #AndroidDev #iOSDev #CleanArchitecture #MVVM #ViewModelScoping</blockquote><p>Publish Date — 1 Feb 2026</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ea62b846ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>