- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 280字
- 2021-08-05 10:46:51
Summary
This chapter covered many interesting topics of practical concurrency in Kotlin. Let's do a recap of the key topics.
- Android applications will throw NetworkOnMainThreadException if a network request is done on the UI thread.
- Android applications can only update the UI on the UI thread, and trying to do it from a different thread will produce a CalledFromWrongThreadException.
- Network requests have to be done in a background thread. The information has to be sent to the UI thread for the views to be updated.
- A CoroutineDispatcher can be used to enforce a coroutine to run in a specific thread, or group of threads.
- One or many coroutines can be run in a thread by using launch or async.
- launch should be used in fire-and-forget scenarios, meaning cases where we aren't expecting the coroutine to return something.
- async should be used when the coroutine will produce a result that will be processed. Using async without handling its result can result in exceptions not being propagated.
- Kotlin has specific libraries for Android, Swing, JavaFX, and more. Each of them offers a proper coroutine dispatcher to update UI elements.
- There are many ways to write concurrent code, and it's important to understand how to make the best of Kotlin's flexibility while being explicit, safe, and consistent.
In the next chapter, we will cover what a Job is in more detail, how to create a hierarchy of jobs to control chained events, and how to use chaining to stop jobs when they are no longer needed. We will also work on displaying the news obtained from the feed in a recycler view and in adding error handling when a feed can't be reached.
推薦閱讀
- 潮流:UI設(shè)計(jì)必修課
- Mastering Articulate Storyline
- Java Web及其框架技術(shù)
- Mastering Yii
- 可解釋機(jī)器學(xué)習(xí):模型、方法與實(shí)踐
- Clojure Reactive Programming
- Python極簡講義:一本書入門數(shù)據(jù)分析與機(jī)器學(xué)習(xí)
- Python語言實(shí)用教程
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- C/C++數(shù)據(jù)結(jié)構(gòu)與算法速學(xué)速用大辭典
- HTML+CSS+JavaScript網(wǎng)頁設(shè)計(jì)從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- ArcGIS for Desktop Cookbook
- PHP 7從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- Web App Testing Using Knockout.JS
- Solr權(quán)威指南(下卷)