https://kotlinlang.org logo
#compose
Title
# compose
m

Martin Nonnenmacher

03/06/2022, 1:02 PM
Hi, I'm using
collectAsState()
with a flow that emits new values very frequently, about 10 times a second. The problem is that the
SnapshotStateObserver.applyMaps
property keeps growing and consumes more and more memory over time. This can be reproduced with the code below. A heap dump shows that after 50,000 iterations there is a single instance of
androidx.compose.runtime.snapshots.SnapshotStateObserver$ApplyMap[]
that consumes about 100 MB. As it seems to be by design that
applyMaps
can only grow, is there a fundamental issue with my code, or is there another approach I could use for frequent updates without eventually running out of memory?
Copy code
class TestState {
    private val scope = CoroutineScope(Dispatchers.Default)
    val value = MutableStateFlow(0)

    init {
        scope.launch {
            while (true) {
                value.value = value.value + 1
                delay(100)
            }
        }
    }
}

@Composable
fun App() {
    val state = remember { TestState() }
    val value = state.value.collectAsState()
    Text("value = ${value.value}")
}
👀 3
z

Zach Klippenstein (he/him) [MOD]

03/08/2022, 12:57 AM
I don't see anything there that should cause a memory leak aside from that scope never getting cancelled, but it sounds like we're leaking proportionally with time which that shouldn't do. Can you file a bug?
o

olonho

03/08/2022, 8:29 PM
m

Martin Nonnenmacher

03/08/2022, 8:45 PM
Just saw the response, @olonho thanks for creating the issue!
2 Views