Kotlin- Coroutines read file

110 Views Asked by At

Main function:

val users = CoroutineScope(Dispatchers.IO).launch{readFile()}.toString()

readFile:

suspend fun readFile(): String = withContext(Dispatchers.IO){
    .............
    return@withContext fullString
}

I'm not sure if my code is good, because im creating 2 coroutines. first one is by using CoroutineScope (Dispatchers.IO) and second one is in readfile using withContext. what is the best approach to this?

Read file using coroutines

1

There are 1 best solutions below

0
On

You're not creating two coroutines. The launch call creates a coroutine. The withContext call doesn't create a new coroutine, it just modifies the conditions of the currently running coroutine that calls the function that uses it.

Note, your users variable is launching an asynchronous coroutine, and then calling toString() on the returned Job, which is likely not what you intended. You cannot get the result of a coroutine from outside that coroutine unless you use async instead of launch and call await() on the returned Deferred. But you can only call await() on it if you are inside a coroutine.