- 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.
推薦閱讀
- Functional Python Programming
- Rust編程:入門、實戰與進階
- AIRAndroid應用開發實戰
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- Java Web基礎與實例教程
- Spring Boot Cookbook
- Kotlin編程實戰:創建優雅、富于表現力和高性能的JVM與Android應用程序
- Android應用開發深入學習實錄
- Android嵌入式系統程序開發:基于Cortex-A8(第2版)
- SEO教程:搜索引擎優化入門與進階(第3版)
- Node.js實戰:分布式系統中的后端服務開發
- 安卓工程師教你玩轉Android
- C++ Data Structures and Algorithm Design Principles
- PHP程序設計高級教程
- 現代JavaScript編程:經典范例與實踐技巧