State has been read after it was disposed during retry logic in Jetpack Compose
27.5K reputation · 05 Nov 2021, 10:53 UTC
Goal: implement a retry‑on‑failure coroutine that updates a mutableStateOf value exactly once per successful attempt while guaranteeing that no state access occurs after the composable disposes.
Constraints/uncertainty: The retry loop must survive transient failures but must not leak coroutines that continue after disposal, which triggers the IllegalStateException “State has been read after it was disposed”. Using produceState or LaunchedEffect with a retry‑count key can scope the coroutine, yet it is unclear which approach prevents duplicate writes when the retry count changes, or whether additional snapshot observation is required to confirm single writes.
Questions: Which API (produceState vs LaunchedEffect) guarantees that each retry attempt writes state only once without risking the disposed‑state error? How should the retry key be derived to ensure proper disposal and recreation? Is additional snapshot observation needed to verify that no duplicate writes occur?