Hi, I have a function that does a lengthy operatio...
# android
r
Hi, I have a function that does a lengthy operation, but I want it to return only after this operation is completed. Also I would like the caller of the function to call it inside a coroutine because it could block them. I did something like:
Copy code
suspend fun foo(){
        runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
            // do some operation and return only after it's completed
        }
    }
How ever adding the suspend modifier gave me the following warning (posted in reply).
Screen Shot 2021-09-13 at 2.05.40 PM.png
not sure how to handle the case I described above; make the function return after it has completed the operation and let the caller use coroutine. thoughts?
d
#coroutines would be a better fit for this question.
runBlocking
will block the current thread. Does the operation you do in place of your comment is a thread-blocking operation? If that is the case, I believe what you want to use is
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
. In what context do call your
foo
method? Also, the Coroutines guide is very helpful.
r
if I used
Copy code
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
then the function would return immediately. How I want it to return only when the operation is completed. I call
foo
from something like :`lifecycleScope.launch(Dispatachers.IO){foo}`
thanks for your suggestion. I will start asking coroutine related questions in the correct channel
r
Look up for Deferred type