Hyun
06/24/2020, 5:00 AMTextButton.onClick
.
as onClick
is not Composable.
I can’t use launchInComposition
so, I tried the below. but I’m not sure if this is proper approach or not.
I searched on this channel but. it was difficult to find the discussion.
scope = remember { CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) }
onDispose { scope.cancel() }
TextButton(onClick={ scope.launch { doSuspendFunction() }})
what is the best approach on this case?Leland Richardson [G]
06/24/2020, 5:26 AMlaunchInComposition
uses which will work a little bit better but for the most part I think this would work okay:
class ComposableCoroutineScopeImpl(
val context: CoroutineContext
) : CoroutineScope, CompositionLifecycleObserver {
val job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + job
override fun onEnter() {}
override fun onLeave() { job.cancel() }
}
@Composable
fun composableCoroutineScope(
context: CoroutineContext = EmptyCoroutineContext
): CoroutineScope = remember {
ComposableCoroutineScopeImpl(context)
}
Hyun
06/24/2020, 5:42 AMscope = composableCoroutineScope()
TextButton(onClick={ scope.launch { doSuspendFunction() }})
Zach Klippenstein (he/him) [MOD]
06/24/2020, 2:20 PMonDispose
and CompositionLifecycleListener.onLeave
different? I thought the former would not get called if the composition failed before committing, and if that's true for the latter as well that means this code could leak the job/coroutine.
https://kotlinlang.slack.com/archives/CJLTWPH7S/p1591660760450000?thread_ts=1591653158.447300&cid=CJLTWPH7SLeland Richardson [G]
06/24/2020, 4:12 PMscope.launch
in the composition, only in an event handler or something like the original question had