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

James Ward

11/06/2020, 3:23 PM
Can anyone point me to an example where a component event handler function calls a suspend fun? I'm trying:
Copy code
@Composable
fun MyButton() {
    Button(onClick = {
        launchInComposition {
            delay(10)
        }
    }) {
        Text("hello, world")
    }
}
And getting:
@Composable invocations can only happen from the context of a @Composable function
👋 1
Don't know if this is correct, but it seems to work:
Copy code
@Composable
fun MyButton() {
    val scope = remember { CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) }

    onActive { onDispose { scope.cancel() } }

    Button(onClick = {
        scope.launch {
            delay(1000)
            println("asdf")
        }
    }) {
        Text("hello, world")
    }
}
g

Grigorii Yurkov

11/06/2020, 4:08 PM
rememberCoroutineScope()
☝️ 1
2 Views