blob: 0a0a36193100d9860984e23791e03258260de335 [file] [log] [blame]
Roman Elizarov331750b2017-02-15 17:59:17 +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.rx1
18
Roman Elizarov9fe5f462018-02-21 19:05:52 +030019import kotlinx.coroutines.experimental.*
20import org.junit.*
21import rx.*
22import kotlin.coroutines.experimental.*
Roman Elizarov331750b2017-02-15 17:59:17 +030023
24class ObservableBackpressureTest : TestBase() {
25 @Test
26 fun testCancelWhileBPSuspended() = runBlocking<Unit> {
27 expect(1)
Roman Elizarov43e3af72017-07-21 16:01:31 +030028 val observable = rxObservable(coroutineContext) {
Roman Elizarov331750b2017-02-15 17:59:17 +030029 expect(5)
30 send("A") // will not suspend, because an item was requested
31 expect(7)
32 send("B") // second requested item
33 expect(9)
34 try {
35 send("C") // will suspend (no more requested)
36 } finally {
Roman Elizaroved698542017-07-12 13:16:30 +030037 expect(13)
Roman Elizarov331750b2017-02-15 17:59:17 +030038 }
39 expectUnreached()
40 }
41 expect(2)
42 val sub = observable.subscribe(object : Subscriber<String>() {
43 override fun onStart() {
44 expect(3)
45 request(2) // request two items
46 }
47
48 override fun onNext(t: String) {
49 when (t) {
50 "A" -> expect(6)
51 "B" -> expect(8)
52 else -> error("Should not happen")
53 }
54 }
55
56 override fun onCompleted() {
Roman Elizaroved698542017-07-12 13:16:30 +030057 expect(11)
Roman Elizarov331750b2017-02-15 17:59:17 +030058 }
59
60 override fun onError(e: Throwable) {
61 expectUnreached()
62 }
63 })
64 expect(4)
65 yield() // yield to observable coroutine
66 expect(10)
Roman Elizaroved698542017-07-12 13:16:30 +030067 sub.unsubscribe() // now unsubscribe -- shall cancel coroutine & immediately signal onComplete
68 expect(12)
Roman Elizarov7a7b0092017-06-26 14:25:56 +030069 yield() // shall perform finally in coroutine & invoke onCompleted
Roman Elizarov331750b2017-02-15 17:59:17 +030070 finish(14)
71 }
72}