Hey team, I’m running into an issue with `DisposableEffect` and `onDispose` timing in a navigation g...
l
Hey team, I’m running into an issue with
DisposableEffect
and
onDispose
timing in a navigation graph, can anyone help. Detail see 🧵
I have two composable pages:
Copy code
composable<Page1> {
    DisposableEffect(Unit) {
        // 1. set status bar color
        onDispose {
            // 2. reset status bar color
        }
    }
}

composable<Page2> {
    DisposableEffect(Unit) {
        // 3. set status bar color
        onDispose {
            // 4. reset status bar color
        }
    }
}
When I navigate from Page1 → Page2, I expected the execution order to be 1 → 2 → 3 so the status bar color is correct. But what actually happens is 1 → 3 → 2, so Page2’s color gets overridden by Page1’s onDispose. Has anyone dealt with this timing issue before? What’s the recommended way to handle setting/resetting the status bar color in Compose navigation?
z
That makes sense, if the screen transition is animated, then both screens would be in the composition for some period of time
The way I usually solve this sort of thing is to associate some sort of ownership token with the initial set that will cause the reset to be ignored if the token no longer owns the resource.
Eg your status bar manager’s set method returns a disposable callback, stores that callback in a private field in the manager. When the dispose callback is invoked it noops if the field doesn’t still reference the callback.
l
Thanks Zach, sounds like having a ownership token is the way to go, let me try that 👍
z
That said, if you support predictive back, you also need to consider the case where the user starts to swipe back to page 1, which would change the status bar, but then cancels the gesture and stays on page 2.
🤔 1
You might want to consider using LifecycleResumedEffect instead of DisposableEffect which I believe should handle this automatically with nav3.
👀 2