SokolovaMaria | 693142c | 2019-07-17 17:20:29 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.reactor |
| 2 | |
| 3 | import kotlinx.coroutines.ExperimentalCoroutinesApi |
| 4 | import reactor.util.context.Context |
| 5 | import 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 |
| 35 | public 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 |
| 44 | public fun Context.asCoroutineContext(): ReactorContext = ReactorContext(this) |