blob: 5f07ba4972a66b9f803a638056294e4b16ea54ab [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.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 Tolstopyatovd100a3f2019-07-16 16:14:35 +030017) = publish<R>(context) {
Roman Elizarovc961fb62019-04-24 13:01:49 +030018 collect { // collect the source stream
Roman Elizarov86349be2017-03-17 16:47:37 +030019 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)
Vsevolod Tolstopyatovd100a3f2019-07-16 16:14:35 +030030 .fusedFilterMap(Dispatchers.Unconfined, { it % 2 == 0}, { "$it is even" })
Vsevolod Tolstopyatov0685dc42019-04-24 12:16:56 +030031 .collect { println(it) } // print all the resulting strings
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030032}