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, |
| 25 | block: suspend CoroutineScope.() -> Unit): WriterJob { |
| 26 | val coroutine = WriterCoroutine(newCoroutineContext(coroutineContext), channel) |
| 27 | coroutine.initParentJob(coroutineContext[Job]) |
| 28 | block.startCoroutine(coroutine, coroutine) |
| 29 | return coroutine |
| 30 | } |
| 31 | |
| 32 | fun writer(coroutineContext: CoroutineContext, |
| 33 | autoFlush: Boolean = false, |
| 34 | block: suspend CoroutineScope.() -> Unit): WriterJob = writer(coroutineContext, ByteChannel(autoFlush), block) |
| 35 | |
| 36 | private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel) |
| 37 | : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob |
| 38 | |