具有超时结果的 Kotlin Flow

max*_*max 6 android kotlin android-workmanager kotlin-coroutines kotlin-flow

我正在尝试在 CoroutineWorker(WorkManager) 中使用 Flow,并且该流应该侦听存储库中的值 5 秒,如果您在该时间范围内获得该值,则返回 Result.success() 然后忽略/取消计时器,如果时间过去了,则返回 Result.failure()

现在我有类似的事情,我正在尝试将超时纳入其中。

 repository.getListeningValue.onEach {
     //doStuff here with the result
 }.map{
     Result.success()
 }.first()
Run Code Online (Sandbox Code Playgroud)

niq*_*eco 10

我会尝试这样的事情:

withTimeoutOrNull(5_000) {
    flow.first()
    Result.success()
} ?: Result.failure()
Run Code Online (Sandbox Code Playgroud)

我自己没有尝试过,但我认为它应该有效。