blob: e6428b926029e9531ef3c341568f058bce968b75 [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.basic05
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03007
Roman Elizarov9fe5f462018-02-21 19:05:52 +03008import io.reactivex.schedulers.*
Roman Elizarov0950dfa2018-07-13 10:33:25 +03009import kotlinx.coroutines.*
10import kotlinx.coroutines.rx2.*
11import kotlin.coroutines.*
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030012
Prendota65e6c8c2018-10-17 11:51:08 +030013fun main() = runBlocking<Unit> {
Roman Elizarov86349be2017-03-17 16:47:37 +030014 // coroutine -- fast producer of elements in the context of the main thread
Vsevolod Tolstopyatovbbaf99d2018-09-11 15:55:56 +030015 val source = rxFlowable {
Roman Elizarov3f871642017-04-17 15:46:54 +030016 for (x in 1..3) {
Roman Elizarov86349be2017-03-17 16:47:37 +030017 send(x) // this is a suspending function
Roman Elizarov3f871642017-04-17 15:46:54 +030018 println("Sent $x") // print after successfully sent item
Roman Elizarov86349be2017-03-17 16:47:37 +030019 }
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 Elizarov3f871642017-04-17 15:46:54 +030026 Thread.sleep(500) // 500ms to process each item
27 println("Processed $x")
Roman Elizarov86349be2017-03-17 16:47:37 +030028 }
Roman Elizarov3f871642017-04-17 15:46:54 +030029 delay(2000) // suspend the main thread for a few seconds
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030030}