Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | db0ef0c | 2019-07-03 15:02:44 +0300 | [diff] [blame] | 2 | * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | // This file was automatically generated from coroutines-guide-reactive.md by Knit tool. Do not edit. |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 6 | package kotlinx.coroutines.rx2.guide.operators02 |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 7 | |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 8 | import kotlinx.coroutines.* |
| 9 | import kotlinx.coroutines.reactive.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 10 | import org.reactivestreams.* |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 11 | import kotlin.coroutines.* |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 12 | |
| 13 | fun <T, R> Publisher<T>.fusedFilterMap( |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 14 | context: CoroutineContext, // the context to execute this coroutine in |
| 15 | predicate: (T) -> Boolean, // the filter predicate |
| 16 | mapper: (T) -> R // the mapper function |
Vsevolod Tolstopyatov | d100a3f | 2019-07-16 16:14:35 +0300 | [diff] [blame] | 17 | ) = publish<R>(context) { |
Roman Elizarov | c961fb6 | 2019-04-24 13:01:49 +0300 | [diff] [blame] | 18 | collect { // collect the source stream |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 19 | if (predicate(it)) // filter part |
| 20 | send(mapper(it)) // map part |
| 21 | } |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 22 | } |
| 23 | |
Vsevolod Tolstopyatov | bbaf99d | 2018-09-11 15:55:56 +0300 | [diff] [blame] | 24 | fun CoroutineScope.range(start: Int, count: Int) = publish<Int> { |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 25 | for (x in start until start + count) send(x) |
| 26 | } |
| 27 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 28 | fun main() = runBlocking<Unit> { |
Vsevolod Tolstopyatov | bbaf99d | 2018-09-11 15:55:56 +0300 | [diff] [blame] | 29 | range(1, 5) |
Vsevolod Tolstopyatov | d100a3f | 2019-07-16 16:14:35 +0300 | [diff] [blame] | 30 | .fusedFilterMap(Dispatchers.Unconfined, { it % 2 == 0}, { "$it is even" }) |
Vsevolod Tolstopyatov | 0685dc4 | 2019-04-24 12:16:56 +0300 | [diff] [blame] | 31 | .collect { println(it) } // print all the resulting strings |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 32 | } |