blob: d1ce00c67e18bb233fedf101fed8e19e099a95e4 [file] [log] [blame]
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 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.operators02
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
13fun <T, R> Publisher<T>.fusedFilterMap(
Roman Elizarov86349be2017-03-17 16:47:37 +030014 context: CoroutineContext, // the context to execute this coroutine in
15 predicate: (T) -> Boolean, // the filter predicate
16 mapper: (T) -> R // the mapper function
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030017) = GlobalScope.publish<R>(context) {
Roman Elizarov86349be2017-03-17 16:47:37 +030018 consumeEach { // consume the source stream
19 if (predicate(it)) // filter part
20 send(mapper(it)) // map part
21 }
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030022}
23
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030024fun CoroutineScope.range(start: Int, count: Int) = publish<Int> {
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030025 for (x in start until start + count) send(x)
26}
27
Prendota65e6c8c2018-10-17 11:51:08 +030028fun main() = runBlocking<Unit> {
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030029 range(1, 5)
Roman Elizarov43e3af72017-07-21 16:01:31 +030030 .fusedFilterMap(coroutineContext, { it % 2 == 0}, { "$it is even" })
Roman Elizarov86349be2017-03-17 16:47:37 +030031 .consumeEach { println(it) } // print all the resulting strings
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030032}