Statistics
4
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-13

AuthorSam Cooper

Get the efficiency of asynchronous processing without the compromises. Break free from the outdated trade-offs of callbacks and futures, and enjoy the best of both worlds when you mix suspending functions right into familiar loops and sequential programs. Identify opportunities, anticipate hazards, and master key functions and concepts through real coding projects that put coroutines in context. Unleash the real potential of your code and your hardware by dividing problems into structured tasks that run concurrently. Then sit back and enjoy the confidence that comes from using tried and tested tools and idioms to ship maintainable, fault-tolerant code. Your code can't afford to waste resources or block important threads. Whether you're juggling dozens of inputs and outputs, keeping user interfaces smooth and snappy, or parallelizing heavy workloads, you need a dependable way to write asynchronous code that's responsive, readable, and reliable. Coroutines combine the...

Tags
No tags
Publisher: The Pragmatic Bookshelf
Publish Year: 2025
Language: 英文
Pages: 371
File Format: PDF
File Size: 5.4 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 Coroutine Confidence
Untangle Your Async, Ship Safety at Speed
by Sam Cooper Version: P1.0 (August 2025)
Copyright © 2025 The Pragmatic Programmers, LLC. This book is licensed to the individual who purchased it. We don't copy-protect it because that would limit your ability to use it for your own purposes. Please don't break this trust—you can use this across all of your devices but please do not share this copy with other members of your team, with friends, or via file sharing services. Thanks. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. About the Pragmatic Bookshelf The Pragmatic Bookshelf is an agile publishing company. We’re here because we want to improve the lives of developers. We do this by creating timely, practical titles, written by programmers for programmers. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com. Our ebooks do not contain any Digital Restrictions Management, and have always been DRM-free. We pioneered the beta book concept, where you can purchase and read a book while it’s still being written, and provide feedback to the author to help make a better book for everyone. Free resources for all purchasers include source code downloads (if applicable), errata and discussion forums, all available on the book's home page at pragprog.com. We’re here to make your life easier. New Book Announcements Want to keep up on our latest titles and announcements, and occasional special offers? Just create an account on pragprog.com (an email address and a password is all it takes) and select the checkbox to receive newsletters. You can also follow us on twitter as @pragprog. About Ebook Formats If you buy directly from pragprog.com, you get ebooks in all available formats for one price. You can synch your ebooks amongst all your devices (including iPhone/iPad, Android, laptops, etc.) via Dropbox. You get free updates for the life of the edition. And, of course, you can always come back and re-download your books when needed. Ebooks bought from the Amazon Kindle store are subject to Amazon's polices. Limitations in Amazon's file format may cause ebooks to display differently on different devices. For more information, please see our FAQ at pragprog.com/#about-ebooks. To learn more about this book and access the free resources, go to https://pragprog.com/book/sckotlin, the book's homepage. Thanks for your continued support, The Pragmatic Bookshelf The team that produced this book includes: Dave Thomas (Publisher), Janet Furlow (COO), Susannah Davidson (Executive Editor), Michael Swaine (Development Editor), Karen Galle (Copy Editor), Potomac Indexing, LLC (Indexing), Gilson Graphics (Layout) For customer support, please contact support@pragprog.com. For international rights, please contact rights@pragprog.com.
Table of Contents   Acknowledgments   Introduction   Who Is This Book For?   Online Resources   What You’ll Need   What’s in This Book? Part I. Best of Both Worlds 1. Wait Without Worrying   What Is a Coroutine?   Suspend Your First Function   Keep the Main Thread Clear   What Have You Learned? 2. Escape From Callback Hell   Plot Your Program’s Path   Reclaim Control-Flow Keywords   Excavate the Indentation Pyramid   What Have You Learned? 3. Start It, Scope It, Stop It   Access Suspending Functions Anywhere   Fix a Scope to Plug a Memory Leak   Get Rid of Unwanted Tasks   What Have You Learned?
4. Split Up to Speed Up   Write Code That Can Multitask   Download Two Things at Once   What Have You Learned? 5. Plan for Any Outcome   Build a Hierarchy of Tasks and Subtasks   Keep Track of Every Exception   Customize Your Error Handling   What Have You Learned? 6. Cooperate with Cancellation   Give a Task a Time Limit   Keep Clear of Cancellation Exceptions   Suspend a Canceled Coroutine   What Have You Learned? 7. Unlock Parallel Processing   Launch Millions of Tasks   Dispatch to Multiple Cores   Teach a Selfish Function to Share   What Have You Learned? Part II. Better Together 8. Call Blocking Functions Safely   Keep Your Functions Honest   Block That Thread, Not This One   Make Hard Work Look Easy   What Have You Learned? 9. Upgrade Every Callback   Mix Coroutines and Futures   Build Your Own Suspension Point   Lift the Continuation Curtain
  What Have You Learned? 10. Go with the Flow   Run, Return, Resume, Repeat   Wrap It Up Safely   Download Page After Page   What Have You Learned? 11. Operate the Reactive Way   Transform from Flow to Flow   End a Flow Early   Publish a Reactive Stream   What Have You Learned? 12. Share Flows, Connect Channels   Communicate Between Coroutines   React to a Repeating Callback   Share Once, Observe Everywhere   What Have You Learned? 13. Unit Test Without Delay   Write Quick Tests for Slow Code   Expand Your Testing Toolkit   What Have You Learned? Copyright © 2025, The Pragmatic Bookshelf.
Early Praise for Kotlin Coroutine Confidence The first tech book I could not put down. Sam has created something truly special; it is brilliantly structured, effortlessly engaging, and full of moments that make complex ideas click. If you are an engineer who loves a well-told technical story, then you will get a lot from this book, maybe even a new appreciation for Kotlin. → Rob Chapman Author of Observability with Grafana A compelling journey through the intricacies of Kotlin coroutines, this book delivers a perfect cocktail of practical wisdom and best practices. It’s a fun and fruitful read whether you’re new to coroutines or looking to deepen your expertise. → Joffrey Bion Senior Developer Sam’s writing is fantastic; he has the ability to reframe knowledge often taken for granted, not only to aid with the matter at hand but to take away as a solid ground for teaching peers. Reading his work makes me a better engineer! → Amy Jo Turner Software Engineer This book is essential reading for folks coming to Kotlin’s approach to concurrency from other languages—whether from Java, JavaScript, C#, or something else. It covers the similarities as well as the important
differences. I will be encouraging my employer to buy some copies and make this required reading for folks working in Kotlin. → Martin Sandiford Senior Engineering Manager Sam has distilled this complex but highly valuable topic into an easily understandable format so we can quickly learn and readily apply it to create high-performance asynchronous applications. → Venkat Subramaniam Award-winning author and Founder, Agile Developer, Inc.
Acknowledgments   One of the things I love most about creating software, and especially about working with Kotlin, is being surrounded by a community of smart, creative, and endlessly helpful people who love what they do. This book only exists because it has just such a group behind it. First and foremost, I must thank my developmental editor, Michael Swaine, for guiding me tirelessly through the process of publishing my first full- length book. I couldn’t have asked for a more knowledgeable and experienced mentor on this journey. I also want to thank Sandra Williams, who patiently coached me through countless early drafts of the opening chapters. The book has benefited immensely from thorough technical reviews by software engineers and fellow authors whose opinions I deeply value and respect. Thank you to Rob Chapman, Venkat Subramaniam, Joffrey Bion, Martin Sandiford, James Baker, and Amy Jo Turner for your time, your support, and your valuable suggestions. In addition to those reviewers, I’m grateful to everyone who read the beta version of the book and took the time to point out opportunities to improve the final release. The entire text has also been meticulously checked and polished by my copy editor, Karen Galle, who has my sincere appreciation. I’m particularly indebted to the legendary Dave Thomas for his insightful feedback, which made this a better book and me a better writer. I also thank Susannah Davidson, Janet Furlow, Dave Rankin, and everyone else at The
Pragmatic Programmers who has contributed to making this book the best it can be. Among that group is Margaret Eldridge, whom I thank for her help with everything from the initial proposal to the book’s presence on forums and social media. Margaret first approached me about writing a book for The Pragmatic Bookshelf in 2023. Here, I also thank Anupam Chugh, along with his team at Better Programming, who welcomed me so warmly into the world of tech authorship and helped me publish the early stories and articles that caught Margaret’s eye. Next, I’m hugely thankful to everyone who’s worked or corresponded with me throughout my Kotlin coroutine career. I’ve learned an immeasurable amount from colleagues, online strangers, and the amazing Kotlin community. Thank you to the team at JetBrains for creating the Kotlin language, and especially to coroutine mastermind Roman Elizarov. Finally, I’m grateful to you for joining me on this journey. Thank you, and enjoy! Copyright © 2025, The Pragmatic Bookshelf.
Introduction   For as long as I’ve been writing code, programming has been a tale of two styles. One is the undisputed heavyweight champion—the original programming paradigm we all know and love. It’s sequential. It’s synchronous. It’s structured. It lays out its statements in a clear and logical parade of loops, function calls, and conditionals. In the other corner is the lightweight challenger. Zipping from thread to thread with freedom and agility, the callbacks and continuations of asynchronous code weave a dancing web that juggles inputs, outputs, and user interactions with unmatched efficiency. Asynchronous programming has long held the advantage when it comes to responsive user interfaces and high throughput. But its stilted, stitched- together style often falls far short of the ergonomic control flow, resource management, and error handling that have earned synchronous programming its unassailable spot at the top. So, for years, the two have been locked in a stalemate. Today, old-fashioned synchronous programming styles are staging a comeback. More and more languages have begun introducing features and frameworks that bridge the gap, letting us write clear and sequential programs that execute with the speed and efficiency of asynchronous code.
Kotlin’s coroutines are part of this renaissance. And with structured concurrency, they have a secret weapon that could turn the tide and solve some of asynchronous programming’s greatest flaws.
Who Is This Book For? If you write Kotlin code, this book is for you. Coroutines have something to offer for almost every program. Whether you build mobile apps, web pages, back-end servers, or something else altogether, you can use the tools and techniques in this book to improve your code and enhance your development experience. For those new to coroutines, the book will take you on a step-by-step journey. We’ll jump right in with a real-world example of an asynchronous program, and we’ll gradually build on that foundation with a new topic in each chapter. You’ll learn how coroutines can upgrade your asynchronous code and how they compare with other tools you might have used, both in Kotlin and in other languages. Perhaps you’ve already started using coroutines, and you’re here to learn more about them. Yes, we’ll answer all those frustrating questions. Why can’t I launch a coroutine there? Why does that function work that way? And what’s this exception doing here? You’ll learn about the unique challenges that come with asynchronous programming and concurrency and understand how each tool in your coroutine toolbox has been carefully designed to help solve these problems.
Online Resources You’ll find a dedicated page[1] for this book on the Pragmatic Bookshelf website. From there, you can download the complete source code for all the examples you’ll be working with. If you’re reading the book in digital form, you’ll also find a handy link above each code snippet that’ll bring you directly to the source file. Got feedback or questions? Follow the links on the book’s webpage to find the DevTalk forum, where you can report a mistake, make a suggestion, or discuss what you’ve learned with other readers.
What You’ll Need Before you start, you should already be familiar with the Kotlin programming language. We will be looking closely at how coroutines work with common control-flow structures—things like functions, loops, and try– catch–finally blocks—so it’ll help if you have a clear understanding of how those basics work in everyday code. As we introduce each topic, we’ll work through a code example where we use coroutines to solve a real-life problem. If you’d like to follow along with the code examples in the book, you’ll also need to be comfortable using an IDE like IntelliJ IDEA or Android Studio, setting up and executing a simple project, and adding dependencies. If you’d rather read the code without running it, that’s fine, too! For simplicity, we’ll run our code examples in a desktop Java environment. They’ve been written and tested using Kotlin 2.1 and Java 21, but they should work fine on any recent version. We won’t include any code examples for other targets, aside from one or two illustrative Android snippets, but when there are changes required to translate the code from platform to platform, we’ll talk about what those are.
What’s in This Book? We’ll begin our journey with a simple program that uses coroutines to wait for outside events without blocking its thread. To do so, we’ll introduce suspending functions, which are the building blocks that give coroutines their power. We’ll compare them to ordinary functions and to other kinds of asynchronous programming. Why use suspending functions instead of callbacks or blocked threads? We’ll build a photo gallery app that demonstrates how coroutines can give us the best of both worlds, keeping our single-threaded user interface code clean and responsive. But why do suspending functions come with extra rules and syntax— restrictions that don’t seem to apply to other solutions like callbacks and futures? As we continue to improve our photo gallery app, we’ll add a coroutine scope and use its coroutine builder functions to add new coroutines to an existing application. We’ll compare this to the ways we might make an asynchronous call in other languages or frameworks, and we’ll see how Kotlin’s approach is protecting us from a memory leak minefield. Coroutines aren’t just for user interface code, and we’ll use them to harness the multitasking power of any asynchronous operation. As we do so, we’ll also learn about the rules that link our tasks together into a safe, structured hierarchy. We’ll make sure errors don’t go missing, and we’ll use cooperative cancellation to stop our coroutines becoming resource-stealing zombies. Next, we’ll stage a contest to pit our coroutines against old-fashioned threads. You’ll learn why coroutines are sometimes called lightweight threads, and we’ll use a new coroutine dispatcher to give our coroutines an even bigger speed boost with parallel execution.
[1] Coroutines can interoperate with almost any other asynchronous programming style you can think of. They can even call blocking functions if you use the right dispatcher. You’ll learn some built-in functions and facilities to convert between threads, coroutines, callbacks, and futures, and we’ll even try our hand at creating our own suspension point from scratch. As we near the end of our journey, we’ll introduce flows, using them to encapsulate asynchronous procedures and integrate with Reactive Streams. Since no software is complete without tests, we’ll wrap up with some handy tools and techniques for testing the coroutines we’ve written. Ready to get started? Let’s dive into the world of coroutines and write our first suspending function! Footnotes http://pragprog.com/titles/sckotlin Copyright © 2025, The Pragmatic Bookshelf.
Part 1 Best of Both Worlds Familiar sequential control flow, or responsive user interfaces? Powerful parallel processing, or low-cost lightweight execution? Safe, predictable outcomes, or efficient asynchronous multitasking? It’s a world full of compromises—but it doesn’t have to be. In the first part of this book, you’ll learn to speak the language of coroutines. We’ll unpick all of those difficult choices, and you’ll assemble the coroutine tools and techniques to make them each a thing of the past.