Skip to content

coroutines-guide-ui.md actor job cancellation #1480

@ivanbartsov

Description

@ivanbartsov

coroutines-guide-ui.md uses GlobalScope for scope in it's examples, e.g. in section
At most one current job:

fun View.onClick(action: suspend (View) -> Unit) {
    // launch one actor
    val eventActor = GlobalScope.actor<View>(Dispatchers.Main) {
        for (event in channel) action(event)
    }
    // install a listener to activate this actor
    setOnClickListener { 
        eventActor.offer(it)
    }
}

Unless I missed something, this solution looks like it might pollute GlobalScope with actor jobs, as they're not tied to any finite view-related scope (i.e. multiple rotations of an Android device result in multiple click handler actors dangling). As I see it, ideally, some kind of local fragmentScope/activityScope should be used, for example lifecycle.coroutineScope provided by LifecycleScope (of course, that would involve referencing the android-specific androidx.lifecycle:lifecycle-runtime-ktx lib in the guide, which may or may not be in line with the purpose of the guide). Or probably the issue of managing the jobs may be worth mentioning as a side note next to the code.

I'll gladly help amending the guide via PR if the issue is, in fact, valid, and I apologise in advance if it's not and I just missed some piece of the puzzle.

Activity

elizarov

elizarov commented on Sep 3, 2019

@elizarov
Contributor

@ivanbartsov Thanks. This is indeed a problem with coroutines-guide-ui.md, but it is not the only problem. This whole section needs to be rewritten with Flow and structured concurrency in mind, but we'll undertake it only after the ui-related features of Flow are fully ironed out. However, if you have some reasonably sized patch that fixes the issues of GlobalScope without changing the whole guide structure, then we'll accept PR.

added
guideIssues with the coroutines guide on the website
and removed
docsKDoc and API reference
on Apr 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    guideIssues with the coroutines guide on the website

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @elizarov@ivanbartsov@dkhalanskyjb

        Issue actions

          coroutines-guide-ui.md actor job cancellation · Issue #1480 · Kotlin/kotlinx.coroutines