Skip to content

Commit 588df14

Browse files
authored
Explicitly endorse usage of currentCoroutineContext() over kotlin.coroutines.coroutineContext (#4270)
1 parent a9e8a1e commit 588df14

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

Diff for: kotlinx-coroutines-core/common/src/CoroutineScope.kt

+14-6
Original file line numberDiff line numberDiff line change
@@ -312,15 +312,23 @@ public fun CoroutineScope.ensureActive(): Unit = coroutineContext.ensureActive()
312312

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

0 commit comments

Comments
 (0)