Kotlin Flow with time out result
Asked Answered
O

1

6

I'm trying to use Flow inside a CoroutineWorker (WorkManager) and the flow should be listening for a value in the repository for 5 seconds, if you get the value within that time frame you return Result.success() and then ignore/cancel the timer, if the time passed you return Result.failure().

Right now I have something like that and I'm trying to incorporate the timeout there.

 repository.getListeningValue.onEach {
     //doStuff here with the result
 }.map{
     Result.success()
 }.first()
Outage answered 24/2, 2021 at 16:58 Comment(0)
P
11

I would try something like this:

withTimeoutOrNull(5_000) {
    flow.first()
    Result.success()
} ?: Result.failure()

I haven't tried it myself, but I think it should work.

Piscatorial answered 25/2, 2021 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.