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.reactive |
| 6 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 7 | import kotlinx.coroutines.experimental.* |
| 8 | import org.junit.* |
| 9 | import org.reactivestreams.* |
| 10 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 11 | |
| 12 | class PublisherBackpressureTest : 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 = publish(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 | 58246ca | 2017-07-12 12:58:44 +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 | var sub: Subscription? = null |
| 31 | observable.subscribe(object : Subscriber<String> { |
| 32 | override fun onSubscribe(s: Subscription) { |
| 33 | sub = s |
| 34 | expect(3) |
| 35 | s.request(2) // request two items |
| 36 | } |
| 37 | |
| 38 | override fun onNext(t: String) { |
| 39 | when (t) { |
| 40 | "A" -> expect(6) |
| 41 | "B" -> expect(8) |
| 42 | else -> error("Should not happen") |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | override fun onComplete() { |
Roman Elizarov | 58246ca | 2017-07-12 12:58:44 +0300 | [diff] [blame] | 47 | expect(11) |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 48 | } |
| 49 | |
| 50 | override fun onError(e: Throwable) { |
| 51 | expectUnreached() |
| 52 | } |
| 53 | }) |
| 54 | expect(4) |
| 55 | yield() // yield to observable coroutine |
| 56 | expect(10) |
Roman Elizarov | 58246ca | 2017-07-12 12:58:44 +0300 | [diff] [blame] | 57 | sub!!.cancel() // now unsubscribe -- shall cancel coroutine & immediately signal onComplete |
| 58 | expect(12) |
Roman Elizarov | 7a7b009 | 2017-06-26 14:25:56 +0300 | [diff] [blame] | 59 | yield() // shall perform finally in coroutine & report onComplete |
Roman Elizarov | 331750b | 2017-02-15 17:59:17 +0300 | [diff] [blame] | 60 | finish(14) |
| 61 | } |
| 62 | } |