blob: f70834c693231ace7d5e53ca065f6a457fa74ddb [file] [log] [blame]
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// This file was automatically generated from coroutines-guide-reactive.md by Knit tool. Do not edit.
Roman Elizarova9687a32018-06-29 17:28:38 +030018package kotlinx.coroutines.experimental.rx2.guide.operators03
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030019
Vsevolod Tolstopyatov313978c2018-06-01 15:30:34 +030020import kotlinx.coroutines.experimental.channels.*
Roman Elizarov95981f32017-03-17 18:12:04 +030021import kotlinx.coroutines.experimental.*
22import kotlinx.coroutines.experimental.reactive.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030023import kotlinx.coroutines.experimental.selects.*
24import org.reactivestreams.*
25import kotlin.coroutines.experimental.*
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030026
27fun <T, U> Publisher<T>.takeUntil(context: CoroutineContext, other: Publisher<U>) = publish<T>(context) {
Vsevolod Tolstopyatov313978c2018-06-01 15:30:34 +030028 this@takeUntil.openSubscription().consume { // explicitly open channel to Publisher<T>
29 val current = this
30 other.openSubscription().consume { // explicitly open channel to Publisher<U>
31 val other = this
32 whileSelect {
33 other.onReceive { false } // bail out on any received element from `other`
34 current.onReceive { send(it); true } // resend element from this channel and continue
35 }
36 }
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030037 }
38}
39
40fun rangeWithInterval(context: CoroutineContext, time: Long, start: Int, count: Int) = publish<Int>(context) {
41 for (x in start until start + count) {
42 delay(time) // wait before sending each number
43 send(x)
44 }
45}
46
47fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +030048 val slowNums = rangeWithInterval(coroutineContext, 200, 1, 10) // numbers with 200ms interval
49 val stop = rangeWithInterval(coroutineContext, 500, 1, 10) // the first one after 500ms
50 slowNums.takeUntil(coroutineContext, stop).consumeEach { println(it) } // let's test it
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030051}