Yan Pujante
02/17/2021, 2:24 PMBig Chungus
02/17/2021, 2:32 PMIgor Demin
02/17/2021, 2:44 PMlaunch(Dispatchers.Main) { delay(ms); doStuff() }Yes,
GlobalScope.launch(Dispatchers.Main) { delay(ms); doStuff() }
, if your action should outlive the current Composable.
If your delayed action makes sense only in the current Composable, you can use `rememberCoroutineScope`:
val scope = rememberCoroutineScope()
Button(
onClick = {
scope.launch {
delay(2000)
...
}
}
) {
}
When Composable is disposed, the scope will be cancelled, and action will never be performed.Yan Pujante
02/17/2021, 2:45 PMjim
02/17/2021, 3:51 PMDispatchers.Main
going to run on the UI thread? I haven't verified, but I wouldn't have expected that it would.
Compose applies its UI operations on the AWT event thread. To post an operation to this thread, you can use SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait()
Depending on how you model your state, if you are using the functions (mutableStateOf
, stateListOf
, etc) that Compose provides SnapshotState.kt, you are generally safe to mutate from any thread.Igor Demin
02/17/2021, 3:59 PMIsIf we only use Compose for Desktop, then yes -going to run on the UI thread?Dispatchers.Main
Dispatchers.Main
will use UI thread.
But you are right, the safer way is not to use Dispatchers.Main
and use Dispatchers.Swing
instead.
Any third-party library can override Dispatcher.Main
if it depends on the other coroutine dispatcher (for example, on kotlinx-coroutines-javafx
).Igor Demin
02/17/2021, 4:10 PMyou are generally safe to mutate from any thread.👍 yes, it should be safe. But there are a case, when we want to change multiple states which should be changed synchronously with UI (for example,
isError
and errorMessage
).
If recomposition happens between changes of two states we can see "glitches".
We can combine these states as one single state, or change them in UI thread.Yan Pujante
02/17/2021, 4:17 PMjim
02/17/2021, 6:35 PM