Is there a more standard way of accomplishing this...
# compose
b
Is there a more standard way of accomplishing this in Compose? (My very React inspired solution for holding a reference to a value across renders)
Copy code
data class Ref<T>(var current: T? = null)

@Composable
fun SomeCmpt() {
  var jobRef = remember { Ref<Job>() }

  ...
}
c
I’m not familiar with React, but I think
remember { }
is what you’re looking for
b
I tried that first but reassigning
jobRef
later in the code didn’t seem to work for me.
Copy code
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 { ... }
     }
  }
}
c
remember { }
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:
Copy code
@Composable
fun SomeCmpt(id: Int?) {
  var jobRef: Job? by remember { mutableStateOf(null) }

  LaunchedEffect(id) {
     if (id != null) {
        jobRef = launch { ... }
     }
  }
}
this section in the docs goes into this idea in a bit more detail
b
In this instance I don’t need to update the UI when
jobRef
changes so i was trying to do it without
mutableStateOf
c
Compose code doesn’t work like normal code, anything you change within a
@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()
b
interesting - thanks for the knowledge transfer
s
I don't think "will get lost" is the right way to put it. The variable will in fact be updated, it's just that composition will have no way to be informed about this update, since it's not a state object therefore it's not attached any listeners to it to see those changes.
b
In this particular case i don’t think its necessary for composition to be informed about the value changing because it doesn’t effect how the ui is rendered. The example code above did seem to work as intended in my test
s
Depends what you do with it, it's not always to update some UI, it could also be used as a key to an effect or as a parameter to some other composable function or smth like that. In which cases you'd also want it to be backed inside a MutableState too.