- 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.
推薦閱讀
- Java Web開發(fā)學習手冊
- 企業(yè)級Java EE架構(gòu)設(shè)計精深實踐
- 垃圾回收的算法與實現(xiàn)
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- Mastering Ubuntu Server
- 用戶體驗增長:數(shù)字化·智能化·綠色化
- 編寫高質(zhì)量代碼:改善Objective-C程序的61個建議
- 零代碼實戰(zhàn):企業(yè)級應(yīng)用搭建與案例詳解
- Java編程從入門到精通
- 工業(yè)機器人離線編程
- 交互式程序設(shè)計(第2版)
- 石墨烯改性塑料
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- 超好玩的Scratch 3.5少兒編程
- 從零開始學Unity游戲開發(fā):場景+角色+腳本+交互+體驗+效果+發(fā)布