等待响应的干净方法是什么?

时间:2019-05-12 12:59:28

标签: kotlin rx-java

我正在向服务器发送一条消息(自定义协议,没有HTTP),并希望等待响应。它正在使用以下代码:


class Connection {

val messages: Observable<Message>
fun sendMessageWithAnswer(message: Message, timeout:Int = 10): Observable<Answer> {
        if (!isConnected) {
            return Observable.just(Answer.NoConnection)
        }

       val result = BehaviorSubject.create<Answer>()
       val neverDisposed = messages.filter {
            it.header.messageId == message.header.messageId
        }
        .map { Answer.Success(it) as Answer}
        .mergeWith(Observable.timer(timeout.toLong(), TimeUnit.SECONDS)
        .map { Answer.Timeout })
        .take(1).singleOrError()
        .subscribe(
                {result.onNext(it)},
                {
                    // Should never happen
                    throw IllegalStateException("Waiting for answer failed: $it")
                }
        )
        sendMessage(message)
        return result
    }
}

此解决方案的问题是“ neverDisposed”不会被丢弃,这是内存泄漏吗? 我的其他解决方案不适用于此测试用例:

    @Test
    fun ImmediateAnswer() {
        prepare()
        val message = ...
        val answerObservable = connection.sendMessageWithAnswer(message, timeout = 1)
        connection.receiveMessage(message)
        val answer = answerObservable.test()
        answer.awaitCount(1)
        Thread.sleep(1000)
        Assert.assertEquals(1, answer.valueCount())
        Assert.assertEquals(Answer.Success(message), answer.values()[0])
    }

您对此问题有更清洁的解决方案吗?

0 个答案:

没有答案