Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.experimental.io |
| 2 | |
Roman Elizarov | 96d7a88 | 2017-08-30 15:17:05 +0300 | [diff] [blame] | 3 | import kotlinx.coroutines.experimental.CoroutineScope |
| 4 | import kotlinx.coroutines.experimental.Job |
| 5 | import kotlinx.coroutines.experimental.newCoroutineContext |
| 6 | import kotlin.coroutines.experimental.CoroutineContext |
| 7 | import kotlin.coroutines.experimental.startCoroutine |
Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 8 | |
| 9 | /** |
| 10 | * A coroutine job that is writing to a byte channel |
| 11 | */ |
| 12 | interface WriterJob : Job { |
| 13 | /** |
| 14 | * A reference to the channel that this coroutine is writing to |
| 15 | */ |
| 16 | val channel: ByteReadChannel |
| 17 | } |
| 18 | |
| 19 | interface WriterScope : CoroutineScope { |
| 20 | val channel: ByteWriteChannel |
| 21 | } |
| 22 | |
| 23 | fun writer(coroutineContext: CoroutineContext, |
| 24 | channel: ByteChannel, |
Sergey Mashkov | ea3a418 | 2017-09-11 13:06:54 +0300 | [diff] [blame] | 25 | block: suspend WriterScope.() -> Unit): WriterJob { |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 26 | val newContext = newCoroutineContext(coroutineContext) |
| 27 | val coroutine = WriterCoroutine(newContext, channel) |
| 28 | coroutine.initParentJob(newContext[Job]) |
Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 29 | block.startCoroutine(coroutine, coroutine) |
| 30 | return coroutine |
| 31 | } |
| 32 | |
| 33 | fun writer(coroutineContext: CoroutineContext, |
| 34 | autoFlush: Boolean = false, |
Sergey Mashkov | ea3a418 | 2017-09-11 13:06:54 +0300 | [diff] [blame] | 35 | block: suspend WriterScope.() -> Unit): WriterJob = writer(coroutineContext, ByteChannel(autoFlush), block) |
Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 36 | |
| 37 | private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel) |
| 38 | : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob |
| 39 | |