blob: fb144acc23a189babeb7c2d170f61e97ba8a2f6c [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,
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
32fun writer(coroutineContext: CoroutineContext,
33 autoFlush: Boolean = false,
34 block: suspend CoroutineScope.() -> Unit): WriterJob = writer(coroutineContext, ByteChannel(autoFlush), block)
35
36private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel)
37 : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob
38