Is there anything like derivedStateOf that automat...
# compose
f
Is there anything like derivedStateOf that automatically calculates its value in a given coroutine dispatcher? Something that works like a combination of
Copy code
remember {
    snapshotFlow { state }.mapLatest { state ->
        heavyComputation(state) // indirect, will only update when the flow value updates
    }.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
}.collectAsState(sensibleDefault)
and
Copy code
remember {
    derivedStateOf {
        heavyComputation(state) // direct capture, automatically updates
    }
}
w
What do you mean by automatically updates here? In both examples the updates are driven by the state changing. If you want to produce
State
directly you could use
snapshotFlow
inside of
produceState
, which lets you change dispatchers.
f
Hmm, I guess it wasn't very clear. I'll write another example
Copy code
remember {
    snapshotFlow { state }.mapLatest { state ->
        heavyComputation(state) // indirect, requires all state reads to be able to be passed as a parameter to heavyComputation
    }.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
}.collectAsState(sensibleDefault)
// versus
remember {
    derivedStateOf {
        heavyComputation() // heavyComputation can do its own state reads and they'll be tracked correctly
    }
}
w
Ah, I see. You'd have to use something like Molecule run in a separate dispatcher, which will allow state reads but run composition on a different thread. Although if you want the thread switch on the initial value you'd need to edit Molecule's implementation to support that, because it doesn't have an explicit default value.
f
As in, if I want to compute the initial value off the main thread? I don't need to since they're usually simple (
null
,
emptyList()
, etc.)
w
Sorry, initial value wasn't the right term, it's more so the first calculated value. Composition is synchronous on the first call, so this line in Molecule results in the
heavyComputation
running synchronously with the caller that launched the Molecule. This is how it can return a
StateFlow
without asking for an
initialValue
. You'd have to adjust this to run on the background dispatcher.