blob: e2f836f8e0fee8a3cec324e7d6c2163c21274bc3 [file] [log] [blame]
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// This file was automatically generated from coroutines-guide-reactive.md by Knit tool. Do not edit.
Roman Elizarova9687a32018-06-29 17:28:38 +030018package kotlinx.coroutines.experimental.rx2.guide.basic05
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030019
Roman Elizarov9fe5f462018-02-21 19:05:52 +030020import io.reactivex.schedulers.*
Roman Elizarovf1572ca2017-03-17 18:11:15 +030021import kotlinx.coroutines.experimental.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030022import kotlinx.coroutines.experimental.rx2.*
23import kotlin.coroutines.experimental.*
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030024
Roman Elizarov86349be2017-03-17 16:47:37 +030025fun main(args: Array<String>) = runBlocking<Unit> {
26 // coroutine -- fast producer of elements in the context of the main thread
Roman Elizarov43e3af72017-07-21 16:01:31 +030027 val source = rxFlowable(coroutineContext) {
Roman Elizarov3f871642017-04-17 15:46:54 +030028 for (x in 1..3) {
Roman Elizarov86349be2017-03-17 16:47:37 +030029 send(x) // this is a suspending function
Roman Elizarov3f871642017-04-17 15:46:54 +030030 println("Sent $x") // print after successfully sent item
Roman Elizarov86349be2017-03-17 16:47:37 +030031 }
32 }
33 // subscribe on another thread with a slow subscriber using Rx
34 source
35 .observeOn(Schedulers.io(), false, 1) // specify buffer size of 1 item
36 .doOnComplete { println("Complete") }
37 .subscribe { x ->
Roman Elizarov3f871642017-04-17 15:46:54 +030038 Thread.sleep(500) // 500ms to process each item
39 println("Processed $x")
Roman Elizarov86349be2017-03-17 16:47:37 +030040 }
Roman Elizarov3f871642017-04-17 15:46:54 +030041 delay(2000) // suspend the main thread for a few seconds
Roman Elizarov8a4a8e12017-03-09 19:52:58 +030042}