我创建了一个WebSocket类,它可以发出protobuf(Square Wire(消息。我想要一个扩展函数,只过滤我想要的消息。用法如下:
fun main() {
val webSocket: WebSocket
// ... configure web socket
webSocket.filterMessages<CreateContactResponse>()
.subscribe {
println("Create contact response received")
}
webSocket.filterMessages<DeleteContactResponse>()
.subscribe {
println("Delete contact response received")
}
}
下面是我写的扩展函数。我添加了IDE显示的错误注释。
fun <MESSAGE : Message<*, *>> Websocket.filterMessages(): Flowable<MESSAGE> {
observeMessages()
.filter { it is MESSAGE } // Error: Cannot check for instance of erased type: MESSAGE
.map { it as MESSAGE } // Error: Unchecked cast: Message<*, *> to MESSAGE
}
你们能解释一下我怎样才能像预期的那样工作吗?
MESSAGE
必须具体化,因此必须将其写成
inline fun <reified MESSAGE : Message<*, *>>
Websocket.filterMessages() : Flowable<Message> { ... }