blob: 818a792bac0f073cdc7d8c84b05272a2efae6b3c [file] [log] [blame]
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03001/*
Roman Elizarovdb0ef0c2019-07-03 15:02:44 +03002 * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03003 */
4
5// This file was automatically generated from coroutines-guide-reactive.md by Knit tool. Do not edit.
Roman Elizarov0950dfa2018-07-13 10:33:25 +03006package kotlinx.coroutines.rx2.guide.operators03
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03007
Roman Elizarov0950dfa2018-07-13 10:33:25 +03008import kotlinx.coroutines.channels.*
9import kotlinx.coroutines.*
10import kotlinx.coroutines.reactive.*
11import kotlinx.coroutines.selects.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030012import org.reactivestreams.*
Roman Elizarov0950dfa2018-07-13 10:33:25 +030013import kotlin.coroutines.*
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030014
Vsevolod Tolstopyatovd100a3f2019-07-16 16:14:35 +030015fun <T, U> Publisher<T>.takeUntil(context: CoroutineContext, other: Publisher<U>) = publish<T>(context) {
Vsevolod Tolstopyatov313978c2018-06-01 15:30:34 +030016 this@takeUntil.openSubscription().consume { // explicitly open channel to Publisher<T>
17 val current = this
18 other.openSubscription().consume { // explicitly open channel to Publisher<U>
19 val other = this
20 whileSelect {
Roman Elizarovc961fb62019-04-24 13:01:49 +030021 other.onReceive { false } // bail out on any received element from `other`
22 current.onReceive { send(it); true } // resend element from this channel and continue
Vsevolod Tolstopyatov313978c2018-06-01 15:30:34 +030023 }
24 }
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030025 }
26}
27
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030028fun CoroutineScope.rangeWithInterval(time: Long, start: Int, count: Int) = publish<Int> {
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030029 for (x in start until start + count) {
30 delay(time) // wait before sending each number
31 send(x)
32 }
33}
34
Prendota65e6c8c2018-10-17 11:51:08 +030035fun main() = runBlocking<Unit> {
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030036 val slowNums = rangeWithInterval(200, 1, 10) // numbers with 200ms interval
37 val stop = rangeWithInterval(500, 1, 10) // the first one after 500ms
Vsevolod Tolstopyatovd100a3f2019-07-16 16:14:35 +030038 slowNums.takeUntil(Dispatchers.Unconfined, stop).collect { println(it) } // let's test it
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030039}