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

Coroutine equivalent of Thread.currentThread() requires a !! cast #2159

Closed
qwwdfsad opened this issue Jul 22, 2020 · 2 comments
Closed

Coroutine equivalent of Thread.currentThread() requires a !! cast #2159

qwwdfsad opened this issue Jul 22, 2020 · 2 comments

Comments

@qwwdfsad
Copy link
Member

The closest equivalent to the JVM's Thread.currentThread() for coroutines is

coroutineContext[Job]!!

This !! cast always succeeds, but it draws the developer's attention and brings in uncertainty about the correctness of the code. Here's an example where this concern was raised on Stack Overflow.

Kotlin could provide a function that hides this check, for example:

suspend fun currentJob(): Job = coroutineContext[Job]!!

Originally reported here

@qwwdfsad
Copy link
Member Author

This has the same problem as cancel() and isActive: once we have a suspending variant, it's also convenient to provide extension on CoroutineScope and that's where things go wild:

runBlocking {
    flow {
        currentJob() // <- resolves into extension on `runBlocking` instead of suspending variant
    }.collect().launchIn(Job())

}

@recheej
Copy link
Contributor

recheej commented Sep 12, 2020

@qwwdfsad I think to avoid confusion/conflicts, the CoroutineScope extension currentJob() will need to be a different name than the suspending version. How about currentScopeJob()?

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

2 participants