Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting suspendCancellableCoroutine into callbackFlow

I have the following function.

 suspend fun result() = suspendCancellableCoroutine<Int> {continuation ->
      val callback = object : Callback {
            continuation.resume(value)
      }
 }

and then I call result in a Coroutine as follows:

 someCoroutine {
     when (result()){
          x -> doSomething
          y -> doSomething
           ...
     }
 }

It works, but I keep getting the error when its called again:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught exception: Already resumed, but proposed with update.

I figured I need a callbackFlow instead, but I’m not too sure as to how to implement it. Here’s what I have so far.

 suspend fun result() = callbackFlow<Int> {
      val callback = object : Callback {
            trySendBlocking(value)
      }
      awaitClose()
 }

I’m guessing I have to use collect(), but I don’t know how to process it in the coroutine. Any help would be appreciated.

>Solution :

To use values emitted by Flow you need to use one of the terminal operators, for example collect:

coroutineScope.launch {
   result().collect { value ->
       when (value) {
          x -> doSomething
          y -> doSomething
          ...
       }
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading