Search code examples
androidkotlinkotlin-coroutinesandroid-workmanagerkotlin-flow

Kotlin Flow with time out result


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()

Solution

  • 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.