blob: 5a4ccd040e8d96925e1f5d9ada1ad0157bb351d1 [file] [log] [blame]
SokolovaMaria693142c2019-07-17 17:20:29 +03001package kotlinx.coroutines.reactor
2
3import kotlinx.coroutines.ExperimentalCoroutinesApi
4import reactor.util.context.Context
5import kotlin.coroutines.*
6
7/**
8 * Wraps Reactor's [Context] into [CoroutineContext] element for seamless integration Reactor and kotlinx.coroutines.
9 *
10 * [Context.asCoroutineContext] is defined to add Reactor's [Context] elements as part of [CoroutineContext].
11 *
12 * Reactor builders [mono] and [flux] use this context element to enhance the resulting `subscriberContext`.
13 *
14 * ### Usages
15 * Passing reactor context from coroutine builder to reactor entity:
16 * ```
17 * launch(Context.of("key", "value").asCoroutineContext()) {
18 * mono {
19 * println(coroutineContext[ReactorContext]) // Prints { "key": "value" }
20 * }.subscribe()
21 * }
22 * ```
23 *
24 * Accessing modified reactor context enriched from the downstream:
25 * ```
26 * launch {
27 * mono {
28 * println(coroutineContext[ReactorContext]) // Prints { "key": "value" }
29 * }.subscriberContext(Context.of("key", "value"))
30 * .subscribe()
31 * }
32 * ```
33 */
34@ExperimentalCoroutinesApi
35public class ReactorContext(val context: Context) : AbstractCoroutineContextElement(ReactorContext) {
36 companion object Key : CoroutineContext.Key<ReactorContext>
37}
38
39/**
40 * Wraps the given [Context] into [ReactorContext], so it can be added to coroutine's context
41 * and later used via `coroutineContext[ReactorContext]`.
42 */
43@ExperimentalCoroutinesApi
44public fun Context.asCoroutineContext(): ReactorContext = ReactorContext(this)