How do you cancel coroutines when a (functional) c...
# react
m
How do you cancel coroutines when a (functional) component is unmounted? My first shot. Feels weird 🤔
Copy code
@Suppress("unused")
fun RBuilder.useCoroutineScope(): CoroutineScope {
    val (scope) = useState { CoroutineScope(GlobalScope.newCoroutineContext(Dispatchers.Unconfined)) }
    useEffectWithCleanup(emptyList()) { { scope.cancel() } }
    return scope
}
In component:
Copy code
val scope = useCoroutineScope()
scope.launch { … }
r
that's pretty much what i'm doing as well
j
@Rob Murdock if you put the
val cleanup: RCleanup = { scope.cancel() }
outside of the
useEffectWithCleanUp
body, wouldn't that just recreate that function for nothing anytime
useScope
is called?
r
@Joost Klitsie could be! Haven’t run into any issues I’ve traced back to that at this time. I tend to use this at a wrapper component level and then pass it down (technically I pass down a cached function that lets you use the scope, but… details), so that could be part of why I don’t notice anything.
m
There’s nothing wrong with it. It’s simply unused in subsequent calls and hence an unnecessary object allocation 🙂
👍 1
j
yeah yeah I didn't mean a big issue, just unnecessary 🙂
👍 1