Hey guys! I have a Flow and a suspend function whi...
# coroutines
e
Hey guys! I have a Flow and a suspend function which should return some Result value. How should I collect the values from the flow to be able to return the result? If I use
suspendCoroutine
I can’t use suspend functions inside to call
collect
. What is the most correct way to do that?
Copy code
private suspend fun uploadMedia(
   repository: Repository
): Result = suspendCoroutine { continuation ->
        repository.uploadMedia().collect { // <-- Can't call collect
            when (it) {
            	...
            }
        }
    }
1
h
Why do you want to use
suspendCororoutine
at all? It’s a wrapper for callback code. Just remove it, your function is already
suspend
.
s
Flow.first()
will do this for you
Where
Flow
in your example is
repository.uploadMedia()
e
@streetsofboston @hfhbd The problem is that I want to handle not just one item from the flow, but the whole set. For some of them (progress updates) I will do some action, and for some (success / error) I want to finish the
uploadMedia
method and return Result.
I tried to just use return in the collect block, but I get an error
'return' is not allowed here
Looks like I found the easy solution. I was just overcomplicating this. 🫠
Thank you for help!
l
Also, you almost never want to use
suspendCoroutine
at all because it can prevent cancellation, leading to memory leaks (leaking other unrelated objects) or suspend locks. You want to use
suspendCancellableCoroutine
instead, and handle cancellation correctly when the single-callback based API you're wrapping supports it.
But, yeah, you just needed to call
repository.uploadMedia().collect { … }
here, without wrapping it.
e
Thank you! @louiscad