Skip to content

Explicitly endorse usage of currentCoroutineContext() over kotlin.cor… #4270

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

Merged
merged 1 commit into from
Nov 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions kotlinx-coroutines-core/common/src/CoroutineScope.kt
Original file line number Diff line number Diff line change
Expand Up @@ -312,15 +312,23 @@ public fun CoroutineScope.ensureActive(): Unit = coroutineContext.ensureActive()

/**
* Returns the current [CoroutineContext] retrieved by using [kotlin.coroutines.coroutineContext].
* This function is an alias to avoid name clash with [CoroutineScope.coroutineContext] in a receiver position:
* This function is an alias to avoid name clash with [CoroutineScope.coroutineContext]:
*
* ```
* launch { // this: CoroutineScope
* val flow = flow<Unit> {
* coroutineContext // Resolves into the context of outer launch, which is incorrect, see KT-38033
* currentCoroutineContext() // Retrieves actual context where the flow is collected
* }
* // ANTIPATTERN! DO NOT WRITE SUCH A CODE
* suspend fun CoroutineScope.suspendFunWithScope() {
* // Name of the CoroutineScope.coroutineContext in 'this' position, same as `this.coroutineContext`
* println(coroutineContext[CoroutineName])
* // Name of the context that invoked this suspend function, same as `kotlin.coroutines.coroutineContext`
* println(currentCoroutineContext()[CoroutineName])
* }
*
* withContext(CoroutineName("Caller")) {
* // Will print 'CoroutineName("Receiver")' and 'CoroutineName("Caller")'
* CoroutineScope("Receiver").suspendFunWithScope()
* }
* ```
*
* This function should always be preferred over [kotlin.coroutines.coroutineContext] property even when there is no explicit clash.
*/
public suspend inline fun currentCoroutineContext(): CoroutineContext = coroutineContext