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.basic05 |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 7 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 8 | import io.reactivex.schedulers.* |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 9 | import kotlinx.coroutines.* |
| 10 | import kotlinx.coroutines.rx2.* |
| 11 | import kotlin.coroutines.* |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 12 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 13 | fun main() = runBlocking<Unit> { |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 14 | // coroutine -- fast producer of elements in the context of the main thread |
Vsevolod Tolstopyatov | bbaf99d | 2018-09-11 15:55:56 +0300 | [diff] [blame] | 15 | val source = rxFlowable { |
Roman Elizarov | 3f87164 | 2017-04-17 15:46:54 +0300 | [diff] [blame] | 16 | for (x in 1..3) { |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 17 | send(x) // this is a suspending function |
Roman Elizarov | 3f87164 | 2017-04-17 15:46:54 +0300 | [diff] [blame] | 18 | println("Sent $x") // print after successfully sent item |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 19 | } |
| 20 | } |
| 21 | // subscribe on another thread with a slow subscriber using Rx |
| 22 | source |
| 23 | .observeOn(Schedulers.io(), false, 1) // specify buffer size of 1 item |
| 24 | .doOnComplete { println("Complete") } |
| 25 | .subscribe { x -> |
Roman Elizarov | 3f87164 | 2017-04-17 15:46:54 +0300 | [diff] [blame] | 26 | Thread.sleep(500) // 500ms to process each item |
| 27 | println("Processed $x") |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 28 | } |
Roman Elizarov | 3f87164 | 2017-04-17 15:46:54 +0300 | [diff] [blame] | 29 | delay(2000) // suspend the main thread for a few seconds |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 30 | } |