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

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.

主站蜘蛛池模板: 双鸭山市| 东台市| 陆川县| 繁昌县| 长宁区| 扎兰屯市| 成都市| 宜兰县| 武强县| 睢宁县| 调兵山市| 石家庄市| 延安市| 醴陵市| 漳州市| 会泽县| 绵阳市| 当涂县| 叙永县| 乌拉特后旗| 萨迦县| 永顺县| 延边| 牙克石市| 南丰县| 开阳县| 余姚市| 加查县| 香港| 合山市| 巴林左旗| 张家界市| 时尚| 塘沽区| 禹城市| 江都市| 白山市| 天门市| 永川市| 个旧市| 卢龙县|