官术网_书友最值得收藏!

  • Learning Concurrency in Kotlin
  • Miguel Angel Castiblanco Torres
  • 198字
  • 2021-08-05 10:46:44

Readable

Concurrent code in Kotlin is as readable as sequential code. One of the many problems with concurrency in other languages like Java is that often it's difficult to read, understand, and/or debug concurrent code. Kotlin's approach allows for idiomatic concurrent code:

suspend fun getProfile(id: Int) {
val basicUserInfo = asyncGetUserInfo(id)
val contactInfo = asyncGetContactInfo(id)

createProfile(basicUserInfo.await(), contactInfo.await())
}
By convention, a function that is going to run concurrently by default should indicate this in its name, either by starting with async or ending in Async.

This suspend method calls two methods that will be executed in background threads and waits for their completion before processing the information. Reading and debugging this code is as simple as it would be for sequential code.

In many cases, it is better to write a suspend function and call it inside an async {} or launch {} block, rather than writing functions that are already async. This is because it gives more flexibility to the callers of the function to have a suspend function; that way the caller can decide when to run it concurrently, for example. In other cases, you may want to write both the concurrent and the suspend function.
主站蜘蛛池模板: 茂名市| 彭州市| 许昌市| 兴业县| 平山县| 汝阳县| 潼南县| 阿城市| 三穗县| 宿松县| 姚安县| 东乌珠穆沁旗| 潼关县| 东乡| 莱西市| 鲁山县| 尉犁县| 丹凤县| 社会| 阳曲县| 新沂市| 临沭县| 桃江县| 潼南县| 上虞市| 伊金霍洛旗| 颍上县| 凉城县| 麦盖提县| 浪卡子县| 雷波县| 房产| 山阳县| 峡江县| 讷河市| 天水市| 简阳市| 桐城市| 峨眉山市| 绥芬河市| 大关县|