在 SharedFlow 的 .first() 上设置超时包装器

Setting a timeout wrapper over SharedFlow's .first()

我有一个客户端程序,它向服务器请求一些属性。这些属性之一是 Int,称为 ID。我想将请求发送到服务器并在一个带有超时的干净挂起函数中取回值:

suspend fun requestID(str: String):Int? {

... send message to server

... and get the reply

... return null if timed out

}

val id = connection.requestID("bob")

我尝试通过带有 withTimeout() 的 SharedFlow 执行此操作,但共享流的 firstOrNull() 函数不可取消并且是一个挂起函数。有人有什么建议吗?

Kotlin 提供 withTimeoutOrNull() 正是这样做的:

val id = withTimeoutOrNull(5000) {
    requestIdFromServer(str)
}

其中 requestIdFromServer() 是检索数据的挂起函数。在协程超时的情况下 运行 请求将被取消。