Skip to content

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

Open
@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.

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

    Issue actions