简体   繁体   English

Kotlin-协程读取文件

[英]Kotlin- Coroutines read file

Main function:总机 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.我不确定我的代码是否好,因为我创建了 2 个协程。 first one is by using CoroutineScope (Dispatchers.IO) and second one is in readfile using withContext.第一个是使用 CoroutineScope (Dispatchers.IO),第二个是在 readfile 中使用 withContext。 what is the best approach to this?最好的方法是什么?

Read file using coroutines使用协程读取文件

You're not creating two coroutines.您不是在创建两个协程。 The launch call creates a coroutine. launch调用创建一个协程。 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. withContext调用不会创建新的协程,它只是修改当前正在运行的协程调用使用它的 function 的条件。

Note, your users variable is launching an asynchronous coroutine, and then calling toString() on the returned Job, which is likely not what you intended.请注意,您的users变量正在启动异步协程,然后在返回的 Job 上调用toString() ,这可能不是您想要的。 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.除非您使用async而不是launch并在返回的 Deferred 上调用await() ,否则您无法从协程外部获取协程的结果。 But you can only call await() on it if you are inside a coroutine.但是,如果您在协程中,则只能对其调用await()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM