Statistics
9
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-14

AuthorBabic F., Srivastava N.

No description

Tags
No tags
Language: 英文
Pages: 146
File Format: PDF
File Size: 1.8 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Kotlin Coroutines by Tutorials By Filip Babić and Nishant Srivastava Copyright ©2018 Razeware LLC. Notice of Rights All rights reserved. No part of this book or corresponding materials (such as text, images, or source code) may be reproduced or distributed by any means without prior written permission of the copyright owner. Notice of Liability This book and all corresponding materials (such as source code) are provided on an “as is” basis, without warranty of any kind, express of implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in action of contract, tort or otherwise, arising from, out of or in connection with the software or the use of other dealing in the software. Trademarks All trademarks and registered trademarks appearing in this book are the property of their own respective owners. Kotlin Coroutines by Tutorials Kotlin Coroutines by Tutorials raywenderlich.com 2
Dedications "To my friends and family. And mostly to my loved one. Thank you for being patient and understanding, when I couldn’t grab a cup of coffee or tea and catch up. Huge thanks to everyone who’s supported me throughout the entire process, with positive and motivational encouragement. This wouldn’t have gone as nearly as smooth without you." — Filip Babić "I would like to thank the many people who have made this book possible. To my father, who gave me the desire to be a curious soul and learn more. To my mom, who has supported me all along whenever I have had doubts about my own capabilities as a writer. To my friends, Saachi Chawla and Kirti Dohrey, who have always believed in me during my ups and downs. To people who have directly or indirectly been my mentor and helped me through understanding technology at a deeper level whenever I found myself stuck. And lastly, to the team at raywenderlich.com, my co-author, editors and everyone involved in making this book a reality." — Nishant Srivastava Kotlin Coroutines by Tutorials Kotlin Coroutines by Tutorials raywenderlich.com 3
About the Authors Nishant Srivastava is an author on this book. Nishant is a Sr.Android Engineer at Soundbrenner in Berlin, Germany and an open source enthusiast who spends his time doodling when not hacking on Android. He is a caffeine-dependent life-form and can be found either talking about android libraries or advocating that coffee is the elixir of life at community gatherings. He has been part of two startups in the past (Founding Team Member at OmniLabs, Inc. and one of the first employees at Silverpush) with experience in Android SDK Engineering and Audio Digital Signal Processing(DSP) on Android. While working at his past company (Silverpush), he developed the company’s patented UAB (Unique Audio Beacon) Technology. Filip Babić is an author of this book. He is an experienced Android developer from Croatia, working at the Five Agency, building world- known applications, such as the RosettaStone language-learning application and AccuWeather, the globally known weather reporting app. Previously he worked at COBE d.o.o., a German-owned mobile agency, which is partners with the biggest German media company. He's enthusiastic about the Android ecosystem, focusing extensively on applying Kotlin to Android applications, and building scalable, testable and user-friendly applications. Passionately building up good spirit in local development groups in Croatia, focusing on lectures, education, and engagement of new, aspiring developers in the Croatian IT community. But also pursuing global conferences, meetups, and IT fests. Altruistic when it comes to consulting and mentoring, trying to give help to everyone, whenever possible, motivated by the ideology that the Android ecosystem we live in is only as good as we make it. About the Editors Eric Crawford is a tech editor of this book. Eric is a Senior Software Developer at John Deere, where he bounces between iOS and Android development. Before coming to Deere he did freelance mobile development and serverside web development utilizing Java. In his free time he likes to dabble into other platforms like IOT and cloud computing. Kotlin Coroutines by Tutorials Kotlin Coroutines by Tutorials raywenderlich.com 4
Massimo Carli is the final pass editor of this book. Massimo has been working with Java since 1995 when he co-founded the first Italian magazine about this technology (http://www.mokabyte.it). After many years creating Java desktop and enterprise application, he started to work in the mobile world. In 2001 he wrote his first book about J2ME. After many J2ME and Blackberry applications, he then started to work with Android in 2008. The same year he wrote the first Italian book about Android; best seller on Amazon.it. That was the first of a series of 8 books. he worked at Yahoo and Facebook and he's actually Engineering Tech Lead at Lloyds. He's a musical theatre lover and a supporter of the soccer team S.P.A.L. Manda Frederick is an editor of this book. She has been involved in publishing for over ten years through various creative, educational, medical and technical print and digital publications, and is thrilled to bring her experience to the raywenderlich.com family as Managing Editor. In her free time, you can find her at the climbing gym, backpacking in the backcountry, hanging with her dog, working on poems, playing guitar and exploring breweries. About the Artist Vicki Wenderlich is the designer and artist of the cover of this book. She is Ray’s wife and business partner. She is a digital artist who creates illustrations, game art and a lot of other art or design work for the tutorials and books on raywenderlich.com. When she’s not making art, she loves hiking, a good glass of wine and attempting to create the perfect cheese plate. Kotlin Coroutines by Tutorials Kotlin Coroutines by Tutorials raywenderlich.com 5
Table of Contents: Overview Early Access Edition 11.............................................................. What You Need 12....................................................................... Book License 13............................................................................ Book Source Code & Forums 14............................................. Chapter 1: What Is Asynchronous Programming? 15... Chapter 2: Setting Up Your Build Environments 30....... Chapter 3: Getting Started with Coroutines 42............... Chapter 4: Suspending Functions 53.................................... Chapter 5: Async/Await 54....................................................... Chapter 6: Building Sequences & Iterators with Yield 55............................................................................................. Chapter 7: Coroutine Contexts & Dispatchers 56.......... Chapter 8: Exception Handling & Cancellation 57.......... Chapter 9: Coroutines as State Machines 77.................... Chapter 10: Channels 78........................................................... Chapter 11: Producers & Actors 79...................................... Chapter 12: Broadcast Channels 80..................................... Chapter 13: Coroutine Operators 81................................... Chapter 14: Coroutines & RxKotlin Comparison 82...... Kotlin Coroutines by Tutorials raywenderlich.com 6
Chapter 15: Coroutines on Android: Part 1 83................ Chapter 16: Coroutines on Android: Part 2 123.............. Chapter 17: Coroutines on Android: Part 3 124.............. More Books You Might Enjoy 125......................................... Kotlin Coroutines by Tutorials raywenderlich.com 7
Table of Contents: Extended Early Access Edition 11.............................................................. What You Need 12....................................................................... Book License 13............................................................................ Book Source Code & Forums 14............................................. Chapter 1: What Is Asynchronous Programming? 15... Providing feedback 15........................................................................................................... Why multithreading? 17........................................................................................................ Interacting with the UI thread from the background 18.......................................... Handling work completion using callbacks 21............................................................. Indentation hell 23.................................................................................................................. Using reactive extensions for background work 24................................................... Diving deeper into the complexity of Rx 25.................................................................. A blast from the past 26........................................................................................................ Explaining coroutines: The inner workings 27............................................................. Variations through history 27............................................................................................. Key points 28............................................................................................................................. Where to go from here? 29.................................................................................................. Chapter 2: Setting Up Your Build Environments 30....... Choosing the build environments 30............................................................................... Installing the IntelliJ IDEA 31.............................................................................................. Building the Android environment 36............................................................................. Importing a project 38............................................................................................................ Key points 40............................................................................................................................. Where to go from here? 41.................................................................................................. Chapter 3: Getting Started with Coroutines 42............... Executing routines 42............................................................................................................. Launching a coroutine 43...................................................................................................... Kotlin Coroutines by Tutorials raywenderlich.com 8
Building coroutines 44........................................................................................................... Explaining jobs 46.................................................................................................................... Canceling Jobs 47.................................................................................................................... Digging deeper into coroutines 47.................................................................................... Posting to the UI thread 50.................................................................................................. Key points 52............................................................................................................................. Where to go from here? 52.................................................................................................. Chapter 4: Suspending Functions 53.................................... Chapter 5: Async/Await 54....................................................... Chapter 6: Building Sequences & Iterators with Yield 55............................................................................................. Chapter 7: Coroutine Contexts & Dispatchers 56.......... Chapter 8: Exception Handling & Cancellation 57.......... Exception propagation 58.................................................................................................... Handling exceptions 58......................................................................................................... Callback wrapping 65............................................................................................................. Canceling a coroutine 67...................................................................................................... Key points 75............................................................................................................................. Where to go from here? 76.................................................................................................. Chapter 9: Coroutines as State Machines 77.................... Chapter 10: Channels 78........................................................... Chapter 11: Producers & Actors 79...................................... Chapter 12: Broadcast Channels 80..................................... Chapter 13: Coroutine Operators 81................................... Chapter 14: Coroutines & RxKotlin Comparison 82...... Chapter 15: Coroutines on Android: Part 1 83................ Kotlin Coroutines by Tutorials raywenderlich.com 9
Getting started 84................................................................................................................... Does Android really need coroutines? 86...................................................................... Coroutines 117......................................................................................................................... Introducing Anko 119............................................................................................................. Key points 120........................................................................................................................... Where to go from here? 122................................................................................................ Chapter 16: Coroutines on Android: Part 2 123.............. Chapter 17: Coroutines on Android: Part 3 124.............. More Books You Might Enjoy 125......................................... New to iOS or Swift? 125...................................................................................................... Experienced iOS developer? 127....................................................................................... Want to make games? 140.................................................................................................... Want to learn Android or Kotlin? 144.............................................................................. Kotlin Coroutines by Tutorials raywenderlich.com 10
EEarly Access Edition You’re reading an early access edition of Kotlin Coroutines by Tutorials. As we continue to add chapters to the early access edition of this book, we’ll notify you and let you know how to access the updated versions. We hope you enjoy the preview of this book, and that you’ll come back to help us celebrate more releases of Kotlin Coroutines by Tutorials as we work on the book! The best way to get update notifications is to sign up for our monthly newsletter. This includes a list of the tutorials that came out on raywenderlich.com that month, any important news like book updates or new books, and a list of our favorite development links for that month. You can sign up here: • www.raywenderlich.com/newsletter raywenderlich.com 11
WWhat You Need To follow along with this book, you'll need the following: • IntelliJ IDEA Community Edition 2018.2: Available at https://www.jetbrains.com/ idea/. This is the environment in which you'll develop most of the sample code in this book. • Jave SE Development Kit 8.: Most of the code in this book will be run on the Java Virtual Machine or JVM, for which you need a Java Development Kit or JDK. The JDK can be downloaded from Oracle at http://www.oracle.com/technetwork/java/javase/ downloads/index.html. • Android Studio 3.x.: For the examples about Android described in Section 3, you can the IDE available at https://developer.android.com/studio/. If you haven't installed the latest versions of IntelliJ IDEA Community Edition and JDK 8, be sure to do that before continuing with the book. Chapter 2: "Setting Up Your Build Environments" will show you how to get started with IntelliJ IDEA to run Kotlin coroutines code on the JVM. raywenderlich.com 12
LBook License By purchasing Kotlin Coroutines by Tutorials, you have the following license: • You are allowed to use and/or modify the source code in Kotlin Coroutines by Tutorials in as many apps as you want, with no attribution required. • You are allowed to use and/or modify all art, images and designs that are included in Kotlin Coroutines by Tutorials in as many apps as you want, but must include this attribution line somewhere inside your app: “Artwork/images/designs: from Kotlin Coroutines by Tutorials, available at www.raywenderlich.com.” • The source code included in Kotlin Coroutines by Tutorials is for your personal use only. You are NOT allowed to distribute or sell the source code in Kotlin Coroutines by Tutorials without prior authorization. • This book is for your personal use only. You are NOT allowed to sell this book without prior authorization, or distribute it to friends, coworkers or students; they would need to purchase their own copies. All materials provided with this book are provided on an “as is” basis, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. All trademarks and registered trademarks appearing in this guide are the properties of their respective owners. raywenderlich.com 13
BBook Source Code & Forums This book comes with the source code for the starter and completed projects for each chapter. These resources are shipped with the digital edition you downloaded from store.raywenderlich.com. We’ve also set up an official forum for the book at forums.raywenderlich.com. This is a great place to ask questions about the book or to submit any errors you may find. raywenderlich.com 14
1Chapter 1: What Is Asynchronous Programming? By Filip Babić The UI (user interface) is a fundamental part of almost every application. It’s what users see and interact with in order to do their tasks. More often than not, the applications do complex work, such as talking to external services or processing data from a database. Then, when the work is done, it shows a result, mostly in some form of a message. The UI must be responsive. If the work at hand takes a lot of time to complete, it’s necessary to provide feedback to the users so that they don’t feel like the application has frozen, for example, or that they didn’t click a button properly — or perhaps that the feature doesn’t work at all. In this chapter, you’ll learn how to provide useful information to the users about what’s happening in the application and what different mechanisms exist for working with multiple tasks. You’ll see what problems arise while trying to do complex and long- running synchronous operations and how asynchronous programming comes to rescue. You’ll start off by analyzing the flow of a function that deals with data processing and provides feedback to the user. Providing feedback Suppose you have an application that needs to upload content to a network. When the user selects the Upload button, loading bars or spinners appear to indicate that something is ongoing and the application hasn’t stop working. This information is crucial for a good user experience since no one likes unresponsive applications. But what does providing feedback look like in code? raywenderlich.com 15
Consider the following task wherein you want to upload an image but must wait for the application to complete the upload: fun uploadImage(image: Image) { showLoadingSpinner() // Do some work uploadService.upload(image) // Work’s done, hide the spinner hideLoadingSpinner() } At first glance, the code gives you an idea of what’s happening: • You start by showing a spinner. • You then upload an image. • When complete, you hide the spinner. Unfortunately, it’s not exactly that simple because the spinner contains an animation, and there must be code responsible for that. The showLoadingSpinner function must then contain code such as this: fun showLoadingSpinner() { showSpinnerView() while(running) { rotateSpinnerImage() delay() } } The showSpinnerView displays the actual View component, and the following cycle manages the image rotation. But when does this function actually return? In the uploadImage code, you assumed that the spinner animation was running even after the completion of the showLoadingSpinner function, so that the uploading of the image could start. Looking at the previous code, this is not possible. If the spinner is animating, it means that the showLoadingSpinner has not completed. If the showLoadingSpinner has completed, and so the upload has started, it means that the spinner is not animating anymore. This is happening because when you invoke the showLoadingSpinner function you’re making a blocking call. Blocking calls A blocking call is essentially a function that only returns when it has completed. In the example above, the showLoadingSpinner function prevents the upload of an image because it keeps the main thread of execution busy until it returns. But, when it returns, because the running variable becomes false, the spinner stops rotating. Kotlin Coroutines by Tutorials Chapter 1: What Is Asynchronous Programming? raywenderlich.com 16
So how can you solve this problem and animate the spinner even while the upload function is executing? Simply put, you need additional threads on which to execute your long-running tasks. The main thread is also known as UI thread, because it’s responsible for rendering everything on the screen, and this should be the only thing it does. This means that it should manage the rotation of the spinner but not the upload of the image — that has nothing to do with UI. But if the main thread cannot do it because that isn’t its job, what can execute the upload task? Well, quite simply, you need a new thread on which to execute your long-running tasks! Computers nowadays are far more advanced than they were 10 or 15 years ago. Back in the day computers could only have one thread of execution, making them freeze up often, if you tried to do multiple things at once. But because of technological advancements, your applications support a mechanism known as multi-threading. It’s the art of having multiple threads, where each can process a piece of work, collectively finishing the needed tasks. Why multithreading? There’s always been a hardware limit on how fast computers could be — that’s not really about to change. Moreover, the number of operations a single processor in a computer can complete is reaching the law of diminishing returns. Because of that, technology has steered in the direction of increasing the number of cores each processor has, and the number of threads each core can have running concurrently. This way, you could logically divide any number of tasks between different threads, and the cores could prioritize work by organizing them. And, by doing so, multithreading has drastically improved how computer systems optimize work and the speed of execution. You can apply the same idea to modern applications. For example, rather than spending large amounts of money on servers with better hardware, you can speed up the entire system using multithreading and a smart application of concurrency. Comparing the main and worker threads The main thread, or the UI thread, is the thread responsible for managing the UI. Every application can only have one main thread in order to avoid a classical problem called deadlock that can happen when many threads access the same resources — in Kotlin Coroutines by Tutorials Chapter 1: What Is Asynchronous Programming? raywenderlich.com 17
this case, UI components — in a different order. The other threads, which are not responsible for rendering the UI, are called worker threads or background threads. The ability to allow the execution of multiple threads of control is called multithreading, and the set of techniques in order to control their collaboration and synchronization, is called concurrency. Given this, you can rethink how the uploadImage function should work. The showLoadingSpinner starts a new thread that is responsible for the rotation of the spinner image, which interacts with the main thread just to notify a refresh in the UI. Starting a new thread, the function is now a no blocking call and can returns immediately allowing the image upload to start into its own worker thread. When completed, this background thread will notify the main thread to hide the spinner. Once the program launches a background thread, it can either forget about it or expect some result. You will see how background threads process the result, and communicate it to the main thread, in the following section. Interacting with the UI thread from the background The upload image example demonstrates how important managing threads is. The thread responsible to rotate the spinner image needs to communicate with the main thread in order to refresh the UI at each frame. The worker thread responsible for the actual upload needs, when it completes, to communicate with the previous in order to stop the animation and with the main thread for hiding the spinner. All this must happen without any type of blocks. Knowing how threads communicate is key to achieving the full potential of concurrency. Sharing data In order to communicate, different threads need to share some data. For instance, the thread responsible for the rotation of the spinner image needs to notify the main thread that a new image is ready to be displayed. Sharing data is not simple, and it needs some sort of synchronization that is the main reason for concurrency. What happens, for instance, if the main thread receives a notification that a new image is available and, before displaying it, the image is replaced? In this case, the application would skip a frame and a race condition would happen. You then need some sort of thread safe data structure. This means that the data structure should work correctly even if accessed by multiple threads at the same time. Kotlin Coroutines by Tutorials Chapter 1: What Is Asynchronous Programming? raywenderlich.com 18
Accessing the same data from multiple threads maintaining the correct behavior and good performance, is the real challenge of concurrent programming. There are special cases, however. What if the data is only accessed and never updated? In this case, multiple threads can read the same data without any race condition, and your data structure is referred as immutable. Immutable objects are always thread safe. As a pratical example, take a coffee machine in an office. If two people shared it, and it wasn’t thread safe, they could easily make bad coffee or spill it around and make a mess. As one person started making a mocha latte, but another would want a black coffee, they would ultimately ruin the machine — or worse, the coffee. What are the data structures that you can use in order to safely share data in a thread? The most important data structures are queues and, as a special case, pipelines. Queues Threads usually communicate using queues, and they can act on them as producers or consumers. A producer is a thread that puts information into the queue, and the consumer is the one that reads and uses them. You can think of a queue as a list in which producers append data at the end, and then consumers read data from the top, following a logic called FIFO (First In First Out). Threads usually put data into the queue as objects called messages, which encapsulate the information to share. A queue is not just a container, but provides synchronization in order to allow a thread to consume a message only if it is available, otherwise, it waits if the message is not available. Depending if the queue is a blocking queue, the consumer can block and wait for a new message — or just retry later. Kotlin Coroutines by Tutorials Chapter 1: What Is Asynchronous Programming? raywenderlich.com 19
The same can happen for the producer if the queue is full. Queues are thread safe, so it is possible to have multiple producers and multiple consumers. A great real-life example of queues are fast food lines. Imagine having three lines at a fast food restaraunt. The first line has no customers, so the person working the line is blocked until someone arrives. The second has customers, so the line is slowly getting smaller as the worker serves customers. However, the last line is full of customers, but there’s no one to serve them; this, in turn, blocks the line until help arrives. In this example customers form a queue waiting to consume what the fast food workers are preparing for them. When the food is available, the customer consume it and leaves the queue. Pipelines If you think about pipes, or faucets, and how they work, it’s a fairly simple concept. When you release the pressure by turning the valve, you’re actually requesting water. On the other side of that request, there’s a system that regulates the flow of water. As soon as you make a request, it is blocked until the water comes running — just like a blocking call. The same process is used for pipelines or pipes in programming. There’s a pipe that allows streams of data to flow, and there are listeners. The data is usually a stream of bytes, which the listeners parse into something more meaningful. Kotlin Coroutines by Tutorials Chapter 1: What Is Asynchronous Programming? raywenderlich.com 20