Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | package kotlinx.coroutines.experimental.rx1 |
| 6 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 7 | import kotlinx.coroutines.experimental.* |
| 8 | import org.junit.* |
| 9 | import rx.* |
| 10 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 11 | |
| 12 | class ObservableBackpressureTest : TestBase() { |
| 13 | @Test |
| 14 | fun testCancelWhileBPSuspended() = runBlocking<Unit> { |
| 15 | expect(1) |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 16 | val observable = rxObservable(coroutineContext) { |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 17 | expect(5) |
| 18 | send("A") // will not suspend, because an item was requested |
| 19 | expect(7) |
| 20 | send("B") // second requested item |
| 21 | expect(9) |
| 22 | try { |
| 23 | send("C") // will suspend (no more requested) |
| 24 | } finally { |
Roman Elizarov | ed69854 | 2017-07-12 13:16:30 +0300 | [diff] [blame] | 25 | expect(13) |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 26 | } |
| 27 | expectUnreached() |
| 28 | } |
| 29 | expect(2) |
| 30 | val sub = observable.subscribe(object : Subscriber<String>() { |
| 31 | override fun onStart() { |
| 32 | expect(3) |
| 33 | request(2) // request two items |
| 34 | } |
| 35 | |
| 36 | override fun onNext(t: String) { |
| 37 | when (t) { |
| 38 | "A" -> expect(6) |
| 39 | "B" -> expect(8) |
| 40 | else -> error("Should not happen") |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | override fun onCompleted() { |
Roman Elizarov | ed69854 | 2017-07-12 13:16:30 +0300 | [diff] [blame] | 45 | expect(11) |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 46 | } |
| 47 | |
| 48 | override fun onError(e: Throwable) { |
| 49 | expectUnreached() |
| 50 | } |
| 51 | }) |
| 52 | expect(4) |
| 53 | yield() // yield to observable coroutine |
| 54 | expect(10) |
Roman Elizarov | ed69854 | 2017-07-12 13:16:30 +0300 | [diff] [blame] | 55 | sub.unsubscribe() // now unsubscribe -- shall cancel coroutine & immediately signal onComplete |
| 56 | expect(12) |
Roman Elizarov | 7a7b009 | 2017-06-26 14:25:56 +0300 | [diff] [blame] | 57 | yield() // shall perform finally in coroutine & invoke onCompleted |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 58 | finish(14) |
| 59 | } |
| 60 | } |