blob: 3fea8756967bf9c44e4e5dd642c15a6edbf4de08 [file] [log] [blame]
Roman Elizarov3e342e32018-01-13 20:05:51 +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
17package kotlinx.coroutines.experimental.rx2
18
19import kotlinx.coroutines.experimental.*
20import kotlinx.coroutines.experimental.selects.*
21import org.junit.*
22import org.junit.Assert.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030023import kotlin.coroutines.experimental.*
Roman Elizarov3e342e32018-01-13 20:05:51 +030024
25class ObservableSubscriptionSelectTest() : TestBase() {
26 @Test
27 fun testSelect() = runTest {
28 // source with n ints
29 val n = 1000 * stressTestMultiplier
30 val source = rxObservable(coroutineContext) { repeat(n) { send(it) } }
31 var a = 0
32 var b = 0
33 // open two subs
Marko Devcic1d6230a2018-04-04 20:13:08 +020034 val channelA = source.openSubscription()
35 val channelB = source.openSubscription()
36 loop@ while (true) {
37 val done: Int = select {
38 channelA.onReceiveOrNull {
39 if (it != null) assertEquals(a++, it)
40 if (it == null) 0 else 1
41 }
42 channelB.onReceiveOrNull {
43 if (it != null) assertEquals(b++, it)
44 if (it == null) 0 else 2
45 }
46 }
47 when (done) {
48 0 -> break@loop
49 1 -> {
50 val r = channelB.receiveOrNull()
51 if (r != null) assertEquals(b++, r)
52 }
53 2 -> {
54 val r = channelA.receiveOrNull()
55 if (r != null) assertEquals(a++, r)
Roman Elizarov3e342e32018-01-13 20:05:51 +030056 }
57 }
58 }
Marko Devcic1d6230a2018-04-04 20:13:08 +020059 channelA.cancel()
60 channelB.cancel()
Roman Elizarov3e342e32018-01-13 20:05:51 +030061 // should receive one of them fully
62 assertTrue(a == n || b == n)
63 }
64}