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
You're not creating two coroutines. The
launch
call creates a coroutine. ThewithContext
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 callingtoString()
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 useasync
instead oflaunch
and callawait()
on the returned Deferred. But you can only callawait()
on it if you are inside a coroutine.