Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

android: Add interface MainThreadScope that simplifies CoroutineScope implementation #694

Closed
cypressious opened this issue Oct 10, 2018 · 3 comments

Comments

@cypressious
Copy link
Contributor

cypressious commented Oct 10, 2018

Consider adding an interface

interface MainThreadScope : CoroutineScope {
    val job: Job

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job
}

that simplifies the implementation of CoroutineScope.

If this is considered useful, I would be glad to create a PR.

@fvasco
Copy link
Contributor

fvasco commented Oct 10, 2018

Consider to use an helper class

class CoroutineScopeHelper(dispatcher: CoroutineDispatcher = Dispatchers.Default, job: Job = Job()) : CoroutineScope {
    override val coroutineContext: CoroutineContext = dispatcher + job
}

class MyCode : CoroutineScope by CoroutineScopeHelper(Dispatchers.Main) {

    fun cancel() {
        coroutineContext.cancel()
    }
}

@elizarov
Copy link
Contributor

You can already simplify its implementation in the following way:

class MyClass : CoroutineScope {
    override val coroutineContext: CoroutineContext = Dispatchers.Main + Job()
}

Then, whenever you need to cancel a job, just use coroutineContext.cancel(). Does it help? Do we need to introduce any extra abstraction to ... ? It is already just one line.

@qwwdfsad
Copy link
Collaborator

I've ended up with a more elegant proposal, so I am closing this one.
See #829

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants