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

Mehdi Haghgoo

01/23/2021, 7:41 PM
launchInComposition is gone? Why?
t

Timo Drick

01/23/2021, 7:51 PM
It is renamed to LaunchedEffect
m

Mehdi Haghgoo

01/23/2021, 8:05 PM
What is subject parameter in LaunchedEffect for? What should be passed in?
t

Timo Drick

01/23/2021, 8:06 PM
when you pass mutalbestate variables the effect will start every time the variable changed
🙏 1
a

Adam Powell

01/23/2021, 8:47 PM
Passing MutableState values as LaunchedEffect params is generally a code smell indicating that you're using the effect recomposition as a change observer
You'll usually pass the object you're working with inside the effect
👍 1
m

Mehdi Haghgoo

01/23/2021, 8:48 PM
Does this have anything to do with coroutines?
t

Timo Drick

01/23/2021, 8:49 PM
It is launched as a coroutine which is bound to the lifecycle of the composable
☝️ 1
❤️ 1
a

Adam Powell

01/23/2021, 8:54 PM
As an example, the various flow collect extensions are implemented like this:
Copy code
var currentValue by remember { mutableStateOf(initialValue) }
LaunchedEffect(myFlow) {
  myFlow
    .map { performSomeMappingOf(it) }
    .collect { currentValue = it }
}
the flow object itself is used as the key/subject parameter to
LaunchedEffect
, so if you recompose with a different
myFlow
, it cancels the old collect operation and starts a new one with the new value of
myFlow
people tended to forget to think about keys with
launchInComposition
so it's required now. If you really have no keys and you want it to last initial composition to full removal from composition, you can write
LaunchedEffect(true)
or
LaunchedEffect(Unit)
- just like a
while (true)
loop, this should always make you look a little bit closer to be sure it's what the author really intended to do.
👍 1
2 Views