blob: 372f493f7ab21984aef83ebbd9de72b217279d27 [file] [log] [blame]
Sergey Mashkov25b2bc52017-08-24 21:24:47 +03001package kotlinx.coroutines.experimental.io
2
Roman Elizarov96d7a882017-08-30 15:17:05 +03003import kotlinx.coroutines.experimental.CoroutineScope
4import kotlinx.coroutines.experimental.Job
5import kotlinx.coroutines.experimental.newCoroutineContext
6import kotlin.coroutines.experimental.CoroutineContext
7import kotlin.coroutines.experimental.startCoroutine
Sergey Mashkov25b2bc52017-08-24 21:24:47 +03008
9/**
10 * A coroutine job that is writing to a byte channel
11 */
12interface WriterJob : Job {
13 /**
14 * A reference to the channel that this coroutine is writing to
15 */
16 val channel: ByteReadChannel
17}
18
19interface WriterScope : CoroutineScope {
20 val channel: ByteWriteChannel
21}
22
23fun writer(coroutineContext: CoroutineContext,
24 channel: ByteChannel,
Sergey Mashkovea3a4182017-09-11 13:06:54 +030025 block: suspend WriterScope.() -> Unit): WriterJob {
Roman Elizarove8f694e2017-11-28 10:12:00 +030026 val newContext = newCoroutineContext(coroutineContext)
27 val coroutine = WriterCoroutine(newContext, channel)
28 coroutine.initParentJob(newContext[Job])
Sergey Mashkov25b2bc52017-08-24 21:24:47 +030029 block.startCoroutine(coroutine, coroutine)
30 return coroutine
31}
32
33fun writer(coroutineContext: CoroutineContext,
34 autoFlush: Boolean = false,
Sergey Mashkovea3a4182017-09-11 13:06:54 +030035 block: suspend WriterScope.() -> Unit): WriterJob = writer(coroutineContext, ByteChannel(autoFlush), block)
Sergey Mashkov25b2bc52017-08-24 21:24:47 +030036
37private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel)
38 : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob
39