Brandon Howard
09/20/2022, 5:18 PMdata class Ref<T>(var current: T? = null)
@Composable
fun SomeCmpt() {
var jobRef = remember { Ref<Job>() }
...
}
Casey Brooks
09/20/2022, 5:19 PMremember { }
is what you’re looking forBrandon Howard
09/20/2022, 5:23 PMjobRef
later in the code didn’t seem to work for me.
data class Ref<T>(var current: T? = null)
@Composable
fun SomeCmpt(id: Int?) {
var jobRef = remember<Job?> { null }
LaunchedEffect(id) {
if (id != null) {
jobRef = launch { ... }
}
}
}
Casey Brooks
09/20/2022, 5:26 PMremember { }
will only remember a single value across recompositions, but it’s not a variable that itself can be updated. You’d need to also use mutableStateOf()
for that. So basically, mutableStateOf()
is a box that holds a value, which when updated tells Compose to update the UI. You need to wrap that in remember { }
so Compose remembers you’re using the same box across recomposition.
You’ll commonly see this kind of snippet in Compose code:
@Composable
fun SomeCmpt(id: Int?) {
var jobRef: Job? by remember { mutableStateOf(null) }
LaunchedEffect(id) {
if (id != null) {
jobRef = launch { ... }
}
}
}
Casey Brooks
09/20/2022, 5:28 PMBrandon Howard
09/20/2022, 5:37 PMjobRef
changes so i was trying to do it without mutableStateOf
Casey Brooks
09/20/2022, 5:40 PM@Composable
function that isn’t wrapped in mutableStateOf()
will get lost. Even if it doesn’t need to update, if you want to manage that variable from within Compose, you’ll need to use mutableStateOf()
Brandon Howard
09/20/2022, 5:43 PMStylianos Gakis
09/21/2022, 6:56 AMBrandon Howard
09/21/2022, 1:25 PMStylianos Gakis
09/21/2022, 3:33 PM