首页 > 编程知识 正文

kotlin协程源码分析,Android kotlin 协程

时间:2023-05-06 04:06:28 阅读:196489 作者:1510

kotlin协程

In this tutorial, we’ll be looking into Kotlin Coroutines. Coroutines is a vital concept since asynchronous programming is the way to go over the traditional blocking a thread and polling stuff.

在本教程中,我们将研究Kotlin协程。 协程是一个至关重要的概念,因为异步编程是克服传统的阻塞线程和轮询内容的方法。

Kotlin协程 (Kotlin Coroutines)

Concurrency is vital in programming. Running different tasks on different threads. But sometimes, we as developers can get carried away and create too many Thread objects which would eventually consume a lot of memory and time. Thankfully, Kotlin has introduced Coroutines which are light-weight threads.

并发在编程中至关重要。 在不同的线程上运行不同的任务。 但是有时候,作为开发人员,我们会被带走,创建太多的Thread对象,这些对象最终会占用大量内存和时间。 值得庆幸的是,Kotlin推出了轻量级的协程。

By light-weight threads we mean, Coroutines take less memory and time compared with the default Java threads.
Coroutines though currently in the initial stages only, has a powerful set of libraries which we can use to make the computation stuff easy.

轻量级线程是我们的意思,与默认的Java线程相比,协程占用的内存和时间更少。
虽然协程目前仅处于初始阶段,但它具有一组功能强大的库,我们可以使用它们简化计算工作。

Coroutines computations can be done without blocking other threads.

协程计算可以在不阻塞其他线程的情况下完成。

How?

怎么样?

Suspending Functions is the answer to it.

暂停功能是解决之道。

Suspending functions are introduced with Coroutines and allow us to start the function from where it left off. This aids further in memory optimizations of the CPU and multi-tasking. 协程(Coroutines)引入了暂停功能,使我们可以从中断处开始启动该功能。 这进一步有助于CPU的内存优化和多任务处理。

Unlike blocking a thread, suspending functions are less expensive and do not require a context switching.

与阻塞线程不同,挂起函数的开销较小,并且不需要上下文切换。

A suspending function can be created by adding the modifier suspend to a function.

可以通过将修饰符suspend添加到函数来创建suspend函数。

suspend fun helloSuspend(){println("Hello Suspending Functions")}

A suspending function can be only called from a coroutine or another suspending function.
Coroutine comes up with some popular Coroutine Builders to start a coroutine:

只能从协程或其他暂停函数调用暂停函数。
协程提供了一些流行的协程生成器来启动协程:

launch: This creates a new coroutine. It just fires and forgets. Doesn’t wait for the response. If an exception occurs, it’s an uncaught exception that would abrupt the program flow.

launch :这将创建一个新的协程。 它只是开火而忘记。 不等待响应。 如果发生异常,则它是一个未捕获的异常,它将使程序流突然中断。 async: This fires and waits for the response. The response is of the type

async :这将触发并等待响应。 响应的类型 Deferred<T>. To get the response we invoke await on the function.

Deferred<T> 。 为了获得响应,我们在函数上调用await 。 runBlocking – This is similar to launch except that inside a runblocking everything would be on the same coroutine.

runBlocking –与启动类似,除了在runblocking内部所有内容都在同一协程上。 run – This is a basic coroutine.

run -这是一个基本的协程。 await is a suspending function. await是一个暂停功能。

The equivalent for Thread.sleep is delay function.

Thread.sleep的等效项是delay功能。

import kotlinx.coroutines.experimental.CommonPoolimport kotlinx.coroutines.experimental.delayimport kotlinx.coroutines.experimental.launchsuspend fun helloSuspend(){ println("Hello Suspending Functions")}fun main(args: Array<String>) { println("Start") launch(CommonPool) { delay(2000) helloSuspend() println("Inside launch") } println("Finished") //helloSuspend() //this won't compile}

The output of the above code is:

上面代码的输出是:

The helloSuspend method isn’t run since the function just fires and forgets.

由于该函数只会触发并忘记,因此helloSuspend方法不会运行。

We use the join function which waits for the completion.

我们使用等待完成的联接功能。

import kotlinx.coroutines.experimental.*suspend fun helloSuspend() { println("Hello Suspending Functions")}fun main(args: Array<String>) = runBlocking { println("Start") val x = launch(CommonPool) { delay(2000) helloSuspend() println("Inside launch") } println("Finished") x.join()}

The output now is:

现在的输出是:

We’ve used a runBLocking function as the root coroutine since join is a suspending function and it cannot be invoked outside a coroutine/suspending function.

我们将runBLocking函数用作根协程,因为join是一个挂起函数,不能在协程/挂起函数外部调用它。

import kotlinx.coroutines.experimental.*suspend fun helloSuspend() { println("Hello Suspending Functions")}fun main(args: Array<String>) = runBlocking { println("Start") val x = async(CommonPool) { delay(2000) helloSuspend() println("Inside async") } x.await() println("Finished")}
join waits for completion of launch.
加入等待启动完成。

await looks for the returned result.

等待寻找返回的结果。

import kotlinx.coroutines.experimental.*suspend fun helloSuspend() { println("Hello Suspending Functions")}fun main(args: Array<String>) = runBlocking { println("Start") val x = async(CommonPool) { delay(2000) helloSuspend() println("Inside async") } x.await() println("Finished") run{ println("Inside run") }}//print//Start//Hello Suspending Functions//Inside async//Finished//Inside run

In the following section, in our IntellIJ we’ll be creating an application using Coroutines that fetches url data asynchronously.

在下一节中,我们将在IntellIJ中使用协程创建一个异步获取URL数据的应用程序。

Create a new Gradle Project in your IntelliJ:

在您的IntelliJ中创建一个新的Gradle项目:

In your build.gradle add the following dependencies:

在您的build.gradle中添加以下依赖项:

compile 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5'compile 'khttps:khttps:0.1.0'

Add this block too:

也添加此块:

kotlin { experimental { coroutines "enable" }}

You build.gradle should look like this:

您的build.gradle应该看起来像这样:

Create a new Kotlin file in the Kotlin folder.
IN the following code, we fetch the url’s content through an async coroutine.

在Kotlin文件夹中创建一个新的Kotlin文件。
在以下代码中,我们通过异步协程获取url的内容。

import kotlinx.coroutines.experimental.CommonPoolimport kotlinx.coroutines.experimental.asyncimport kotlinx.coroutines.experimental.launchimport kotlinx.coroutines.experimental.runBlockingsuspend fun fetch(url: String): String { return khttp.get(url).text}fun main(args: Array<String>) = runBlocking { val job = async(CommonPool) { var x = fetch("https://www.journaldev.com") print(x) } val x = launch(CommonPool) { job.await() } x.join()}

In the above code, fetch is a suspending function that’s called inside an async coroutine. await is used to get the return value of the coroutine.
join finally waits for the completion of the coroutine.

在上面的代码中, fetch是一个在async协程内部调用的暂停函数。 await用于获取协程的返回值。
加入终于等待协程的完成。

Following is the output:

以下是输出:

That’s all for Kotlin Coroutines example tutorial.

这就是Kotlin Coroutines示例教程的全部内容。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/20479/kotlin-coroutines

kotlin协程

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。