blob: 12d9c1f6478dce483644acbdbe3ace135c819440 [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.operators04
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03007
Roman Elizarov0950dfa2018-07-13 10:33:25 +03008import kotlinx.coroutines.*
9import kotlinx.coroutines.reactive.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030010import org.reactivestreams.*
Roman Elizarov0950dfa2018-07-13 10:33:25 +030011import kotlin.coroutines.*
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030012
Vsevolod Tolstopyatovd100a3f2019-07-16 16:14:35 +030013fun <T> Publisher<Publisher<T>>.merge(context: CoroutineContext) = publish<T>(context) {
Vsevolod Tolstopyatov0685dc42019-04-24 12:16:56 +030014 collect { pub -> // for each publisher collected
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030015 launch { // launch a child coroutine
Vsevolod Tolstopyatov0685dc42019-04-24 12:16:56 +030016 pub.collect { send(it) } // resend all element from this publisher
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030017 }
18 }
19}
20
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030021fun CoroutineScope.rangeWithInterval(time: Long, start: Int, count: Int) = publish<Int> {
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030022 for (x in start until start + count) {
23 delay(time) // wait before sending each number
24 send(x)
25 }
26}
27
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030028fun CoroutineScope.testPub() = publish<Publisher<Int>> {
29 send(rangeWithInterval(250, 1, 4)) // number 1 at 250ms, 2 at 500ms, 3 at 750ms, 4 at 1000ms
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030030 delay(100) // wait for 100 ms
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030031 send(rangeWithInterval(500, 11, 3)) // number 11 at 600ms, 12 at 1100ms, 13 at 1600ms
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030032 delay(1100) // wait for 1.1s - done in 1.2 sec after start
33}
34
Prendota65e6c8c2018-10-17 11:51:08 +030035fun main() = runBlocking<Unit> {
Vsevolod Tolstopyatovd100a3f2019-07-16 16:14:35 +030036 testPub().merge(Dispatchers.Unconfined).collect { println(it) } // print the whole stream
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030037}