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

  • 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.
主站蜘蛛池模板: 广饶县| 宁海县| 五河县| 航空| 新平| 邵阳市| 金山区| 陆良县| 依安县| 涪陵区| 蚌埠市| 定安县| 资溪县| 清远市| 马公市| 墨竹工卡县| 凤冈县| 宁强县| 湘潭市| 星子县| 布尔津县| 米泉市| 临潭县| 海阳市| 永顺县| 米易县| 华亭县| 贵南县| 含山县| 南华县| 迭部县| 虞城县| 宿州市| 迁西县| 高淳县| 拜城县| 喜德县| 屏南县| 元氏县| 绵阳市| 晋州市|