【问题标题】:Meaning of this code "suspend fun get(url: String) = withContext(Dispatchers.IO){/*...*/}"这段代码的含义“suspend fun get(url: String) = withContext(Dispatchers.IO){/*...*/}”
【发布时间】:2019-08-04 12:27:09
【问题描述】:

我是 android 开发的新手。当我阅读媒体帖子 https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb 时,我遇到了这段代码:

suspend fun get(url: String) = withContext(Dispatchers.IO){/*...*/}

我无法理解。我尝试过搜索,但找不到语法相似的代码。有人可以解释一下吗?

【问题讨论】:

  • 那篇文章试图解释那个特定的代码块。如果您有任何计算机语言的线程经验,引用任何您不理解的文章文本可能会有所帮助。

标签: android kotlin kotlin-coroutines


【解决方案1】:

它与使用Coroutinesasynchronousnon-blocking 编程有关。这是一个挂起函数,可以挂起协程的执行。

withContext 让你的函数返回一个值(你也可以使用launch 它将返回一个工作)。

来自文档:

Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.Read more here.

Dispatchers.IO 是后台协程的默认协程调度器实例。 Read more here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2023-01-16
    • 2021-08-16
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多