Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 1 | /* |
| 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 | package kotlinx.coroutines.experimental.rx2 |
| 18 | |
| 19 | import kotlinx.coroutines.experimental.* |
| 20 | import kotlinx.coroutines.experimental.selects.* |
| 21 | import org.junit.* |
| 22 | import org.junit.Assert.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 23 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 24 | |
| 25 | class 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 Devcic | 1d6230a | 2018-04-04 20:13:08 +0200 | [diff] [blame] | 34 | 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 Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 56 | } |
| 57 | } |
| 58 | } |
Marko Devcic | 1d6230a | 2018-04-04 20:13:08 +0200 | [diff] [blame] | 59 | channelA.cancel() |
| 60 | channelB.cancel() |
Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 61 | // should receive one of them fully |
| 62 | assertTrue(a == n || b == n) |
| 63 | } |
| 64 | } |