Statistics
6
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-15

AuthorFlorent Pillet, Junior Bontognali, Marin Todorov, Scott Gardner

Learn reactive programming in Swift with RxSwift! The popularity of reactive programming continues to grow on an ever-increasing number of platforms and languages. Rx lets developers easily and quickly build apps with code that can be understood by other Rx developers — even over different platforms. Not only will you learn how to use the RxSwift port to create complex reactive applications on iOS, you’ll also see how to easily solve common application design issues by using RxSwift. Finally, you’ll discover how to exercise full control over the library and leverage the full power of reactive programming in your apps. Who This Book Is For This book is for iOS developers who already feel comfortable with iOS and Swift, and want to dive deep into development with RxSwift. Topics Covered in RxSwift Getting Started: Get an introduction to the reactive programming paradigm, learn the terminology involved and see how to begin using RxSwift in your projects. Event Management: Learn how to handle asynchronous event sequences via two key concepts in Rx — Observables and Observers. Being Selective: See how to work with various events using concepts such as filtering, transforming, combining, and time operators. UI Development: RxSwift makes it easy to work with the UI of your apps using RxCocoa, which provides an integration of both UIKit and Cocoa. Intermediate Topics: Level up your RxSwift knowledge with chapters on reactive networking, multi-threading, and error handling. Advanced Topics: Round out your RxSwift education by learning about MVVM app architecture, scene-based navigation, and exposing data via services. And much, much more!

Tags
No tags
Publisher: Razeware LLC
Publish Year: 2017
Language: 英文
Pages: 398
File Format: PDF
File Size: 24.5 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)
RxSwift: Reactive Programming with Swift Florent Pillet, Junior Bontognali, Marin Todorov & Scott Gardner Copyright ©2017 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. RxSwift - Reactive Programming with Swift raywenderlich.com 2
Dedications "For my father." — Marin Todorov "For Fabienne and Alexandra" — Florent Pillet "For my grandfather." — Junior Bontognali "For Betty ! " — Scott Gardner RxSwift - Reactive Programming with Swift raywenderlich.com 3
About the authors Florent Pillet is an author of this book. Florent has been developing for mobile platforms since the last century and moved to iOS on day 1. He adopted reactive programming before Swift was announced and has been using RxSwift in production since 2015. A freelance developer, Florent also uses Rx on Android and likes working on tools for developers like the popular NSLogger when he's not contracting for clients worldwide. Say hello to Florent on Twitter at @fpillet. Junior Bontognali is an author of this book. Junior has been developing on iOS since the first iPhone and joined the RxSwift team in the early development stage. Based in Switzerland, when he's not eating cheese or chocolate, he's doing some cool stuff in the mobile space, without denying to work on other technologies. Other than that he organizes tech events, speaks and blogs. Say hello to Junior on Twitter at @bontoJR. Marin Todorov is an author of this book. Marin is one of the founding members of the raywenderlich.com team and has worked on seven of the team's books. Besides crafting code, Marin also enjoys blogging, teaching, and speaking at conferences. He happily open-sources code. You can find out more about Marin at www.underplot.com. Scott Gardner is an author of this book. Scott has been developing iOS apps since 2010, Swift since the day it was announced, and RxSwift since before version 1. He's authored several video courses, tutorials, and articles on iOS app development, presented at numerous conferences, meetups, and online events, and this is his second book. Say hello to Scott on Twitter at @scotteg. RxSwift - Reactive Programming with Swift raywenderlich.com 4
About the editors Ash Furrow is the technical editor of this book. Ash is a Canadian iOS developer and author, currently working at Artsy. He has published a number of books, built many apps, and is a contributor to the open source community. On his blog ashfurrow.com, he writes about a range of topics, from interesting programming to explorations of analogue film photography. Chris Belanger is the editor of this book. Chris Belanger is the Book Team Lead and Lead Editor for raywenderlich.com. If there are words to wrangle or a paragraph to ponder, he‘s on the case. When he kicks back, you can usually find Chris with guitar in hand, looking for the nearest beach, or exploring the lakes and rivers in his part of the world in a canoe. Marin Todorov is the final pass editor of this book. Marin is one of the founding members of the raywenderlich.com team and has worked on seven of the team's books. Besides crafting code, Marin also enjoys blogging, teaching, and speaking at conferences. He happily open-sources code. RxSwift - Reactive Programming with Swift raywenderlich.com 5
Table of Contents: Overview Introduction 15................................................................................ Section I: Getting Started with RxSwift 21........................ Chapter 1: Hello RxSwift! 22.............................................. Chapter 2: Observables 43................................................ Chapter 3: Subjects 62......................................................... Chapter 4: Observables and Subjects in Practice 76.... Section II: Operators and Best Practices 95....................... Chapter 5: Filtering Operators 96..................................... Chapter 6: Filtering Operators in Practice 114.............. Chapter 7: Transforming Operators 134......................... Chapter 8: Transforming Operators in Practice 146...... Chapter 9: Combining Operators 168............................. Chapter 10: Combining Operators in Practice 188....... Chapter 11: Time Based Operators 208......................... Section III: iOS Apps with RxCocoa 227........................... Chapter 12: Beginning RxCocoa 228............................... Chapter 13: Intermediate RxCocoa 247.......................... Section IV: Intermediate RxSwift/RxCocoa 267................ Chapter 14: Error Handling in Practice 268.................... Chapter 15: Intro To Schedulers 285................................ Chapter 16: Testing with RxTest 299................................. RxSwift - Reactive Programming with Swift raywenderlich.com 6
Chapter 17: Creating Custom Reactive Extensions 314. Section V: RxSwift Community Cookbook 329................. Chapter 18: Table and Collection Views 330................. Chapter 19: Action 334....................................................... Chapter 20: RxGesture 339............................................... Chapter 21: RxRealm 343................................................... Chapter 22: RxAlamofire 348............................................ Section VI: Putting it All Together 352.............................. Chapter 23: MVVM with RxSwift 353.............................. Chapter 24: Building a Complete RxSwift App 375...... Conclusion 398............................................................................... RxSwift - Reactive Programming with Swift raywenderlich.com 7
Table of Contents: Extended Introduction 15................................................................................ What you need 16.................................................................................................................. Who this book is for 16.......................................................................................................... How to use this book 17......................................................................................................... What’s in store 17................................................................................................................... Book source code and forums 18......................................................................................... Book updates 18...................................................................................................................... License 19.................................................................................................................................. About the cover 20.................................................................................................................. Section I: Getting Started with RxSwift 21........................ Chapter 1: Hello RxSwift! 22...................................................... Introduction to asynchronous programming 23.................................................................. Foundation of RxSwift 30....................................................................................................... App architecture 37................................................................................................................ RxCocoa 38.............................................................................................................................. Installing RxSwift 39................................................................................................................ Community 41........................................................................................................................... Where to go from here? 42.................................................................................................. Chapter 2: Observables 43........................................................ Getting started 44.................................................................................................................. What is an observable? 45................................................................................................... Lifecycle of an observable 46.............................................................................................. Creating observables 47....................................................................................................... Subscribing to observables 49.............................................................................................. Disposing and terminating 54............................................................................................... Creating observable factories 59........................................................................................ Challenges 60........................................................................................................................... RxSwift - Reactive Programming with Swift raywenderlich.com 8
Chapter 3: Subjects 62................................................................. Getting started 63.................................................................................................................. What are subjects? 64............................................................................................................ Working with PublishSubjects 64.......................................................................................... Working with BehaviorSubjects 67....................................................................................... Working with ReplaySubjects 69.......................................................................................... Working with Variables 72.................................................................................................... Challenges 74........................................................................................................................... Chapter 4: Observables and Subjects in Practice 76............ Getting started 77.................................................................................................................. Using a variable in a view controller 78............................................................................. Talking to other view controllers via subjects 81............................................................... Which dispose bag to use? 86.............................................................................................. Creating a custom observable 89........................................................................................ Challenges 94........................................................................................................................... Section II: Operators and Best Practices 95....................... Chapter 5: Filtering Operators 96............................................. Getting started 97.................................................................................................................. Ignoring operators 97............................................................................................................. Skipping operators 101......................................................................................................... Taking operators 105............................................................................................................. Distinct operators 109............................................................................................................ Challenges 111........................................................................................................................ Chapter 6: Filtering Operators in Practice 114...................... Improving the Combinestagram project 115...................................................................... Sharing subscriptions 116...................................................................................................... Improving the photo selector 123......................................................................................... Trying out time based filter operators 130........................................................................ Challenges 133........................................................................................................................ RxSwift - Reactive Programming with Swift raywenderlich.com 9
Chapter 7: Transforming Operators 134.................................. Getting started 135................................................................................................................ Transforming elements 135.................................................................................................... Transforming inner observables 138................................................................................... Challenges 143........................................................................................................................ Chapter 8: Transforming Operators in Practice 146.............. Getting started with GitFeed 147....................................................................................... Fetching data from the web 148.......................................................................................... Transforming the response 152............................................................................................. Intermission: Handling erroneous input 157........................................................................ Persisting objects to disk 158................................................................................................ Add a Last-Modified header to the request 159............................................................. Challenges 163........................................................................................................................ Chapter 9: Combining Operators 168...................................... Getting started 169................................................................................................................ Prefixing and concatenating 169......................................................................................... Merging 172............................................................................................................................. Combining elements 174........................................................................................................ Triggers 179............................................................................................................................. Switches 181............................................................................................................................. Combining elements within a sequence 184....................................................................... Challenges 187........................................................................................................................ Chapter 10: Combining Operators in Practice 188............... Getting started 189................................................................................................................ Preparing the web backend service 189........................................................................... Categories view controller 193............................................................................................ Adding the event download service 194............................................................................ Getting events for categories 196....................................................................................... Events view controller 200..................................................................................................... Wiring the days selector 202............................................................................................... Splitting event downloads 204............................................................................................. Challenges 207........................................................................................................................ RxSwift - Reactive Programming with Swift raywenderlich.com 10
Chapter 11: Time Based Operators 208.................................. Getting started 209................................................................................................................ Buffering operators 210........................................................................................................ Time-shifting operators 221.................................................................................................. Timer operators 223............................................................................................................... Challenges 226........................................................................................................................ Section III: iOS Apps with RxCocoa 227........................... Chapter 12: Beginning RxCocoa 228....................................... Getting started 229................................................................................................................ Using RxCocoa with basic UIKit controls 230..................................................................... Binding observables 237....................................................................................................... Improving the code with Units 240....................................................................................... Disposing with RxCocoa 244................................................................................................. Where to go from here? 245................................................................................................ Challenges 246........................................................................................................................ Chapter 13: Intermediate RxCocoa 247.................................. Getting started 248................................................................................................................ Showing an activity while searching 248............................................................................ Extending CCLocationManager to get the current position 251.................................... How to extend a UIKit view 258.......................................................................................... Conclusions about RxCocoa 265........................................................................................... Challenges 266........................................................................................................................ Section IV: Intermediate RxSwift/RxCocoa 267................ Chapter 14: Error Handling in Practice 268............................ Getting started 269................................................................................................................ Managing errors 269............................................................................................................. Handle errors with catch 271................................................................................................ Catching errors 272................................................................................................................ Retrying on error 274............................................................................................................. Custom errors 278................................................................................................................... Advanced error handling 281............................................................................................... Where to go from here? 284................................................................................................ RxSwift - Reactive Programming with Swift raywenderlich.com 11
Challenges 284........................................................................................................................ Chapter 15: Intro To Schedulers 285......................................... What is a Scheduler? 286..................................................................................................... Setting up the project 287..................................................................................................... Switching schedulers 287....................................................................................................... Pitfalls 291................................................................................................................................ Best practices and built-in schedulers 295.......................................................................... Where to go from here? 298................................................................................................ Chapter 16: Testing with RxTest 299......................................... Getting started 300................................................................................................................ Testing operators with RxTest 301........................................................................................ Testing RxSwift production code 307.................................................................................. Chapter 17: Creating Custom Reactive Extensions 314......... Getting started 315................................................................................................................ How to create extensions 315............................................................................................... Use custom wrappers 320...................................................................................................... Testing custom wrappers 321................................................................................................ Common available wrappers 324....................................................................................... Where to go from here? 327................................................................................................ Challenges 328........................................................................................................................ Section V: RxSwift Community Cookbook 329................. Chapter 18: Table and Collection Views 330.......................... Basic table view 330.............................................................................................................. Multiple cell types 332........................................................................................................... Providing additional functionality 333................................................................................ RxDataSources 333................................................................................................................. Chapter 19: Action 334............................................................... Creating an Action 335.......................................................................................................... Connecting buttons 336.......................................................................................................... Composing behavior 336....................................................................................................... Passing work items to cells 337............................................................................................. Manual execution 338............................................................................................................ RxSwift - Reactive Programming with Swift raywenderlich.com 12
Perfectly suited for MVVM 338............................................................................................ Chapter 20: RxGesture 339....................................................... Attaching gestures 339........................................................................................................... Supported gestures 340......................................................................................................... Advanced usage 342.............................................................................................................. Chapter 21: RxRealm 343........................................................... Auto-updating results 343..................................................................................................... Arrays 344................................................................................................................................ Asynchronous first item 344................................................................................................... Changesets 345....................................................................................................................... Single objects 345................................................................................................................... Adding objects 346................................................................................................................. Deleting objects 347............................................................................................................... Chapter 22: RxAlamofire 348.................................................... Basic requests 348................................................................................................................... Request customization 349..................................................................................................... Response validation 350........................................................................................................ Downloading files 350............................................................................................................ Upload tasks 351.................................................................................................................... Tracking progress 351............................................................................................................ Section VI: Putting it All Together 352.............................. Chapter 23: MVVM with RxSwift 353...................................... Introducing MVVM 353.......................................................................................................... Getting started with Tweetie 357........................................................................................ Challenges 372........................................................................................................................ Chapter 24: Building a Complete RxSwift App 375.............. Introducing QuickTodo 376.................................................................................................... Architecting the application 376.......................................................................................... Bindable view controllers 378............................................................................................... Task model 379........................................................................................................................ Tasks service 380..................................................................................................................... Scenes 381................................................................................................................................ RxSwift - Reactive Programming with Swift raywenderlich.com 13
Coordinating scenes 383........................................................................................................ Binding the tasks list with RxDataSources 386................................................................... Binding the Task cell 391........................................................................................................ Editing tasks 392...................................................................................................................... Challenges 395........................................................................................................................ Conclusion 398............................................................................... RxSwift - Reactive Programming with Swift raywenderlich.com 14
IIntroduction "If you've ever used an asynchronous callback based API, you've probably dealt with handling the response data ad-hoc all across your codebase, and have most likely decided there was no way to unit test it all... But, let me tell you - there is a better way, and it's called Rx!" — Krunoslav Zaher, creator of RxSwift There’s no denying it: Rx is one of the hottest topics in mobile app development these days! If you visit international conferences, or even local meetups, it might feel like everyone is talking about observables, side effects, and (gulp) schedulers. And no wonder — Rx is a multi-platform standard, so no matter if it's a web development conference, local Android meetup, or a Swift workshop, you might end up joining a multi-platform discussion on Rx. The RxSwift library (part of the larger family of Rx ports across platforms and languages) allows you to use your favorite Swift programming language in a completely new way. The somewhat difficult-to-handle asynchronous code in Swift becomes much easier and a lot saner to write with RxSwift. To create responsive and robust applications, you have to handle a multitude of concurrent tasks like playing audio, handling user interface input, making networking calls, and more. Sometimes, passing data from one process to another or even just observing that tasks happen in the correct sequence one after another asynchronously might cause the developer a lot of trouble. In this book, you’ll learn how RxSwift solves the issues related to asynchronous programming and master various reactive techniques, from observing simple data sequences, to combining and transforming asynchronous value streams, to designing the architecture and building production quality apps. raywenderlich.com 15
By the end of this book, you’ll have worked through the chapter content and you’ll have hands-on experience solving the challenges at the end of the chapters — and you’ll be well on your way to coming up with your own Rx patterns and solutions! What you need To follow along with the tutorials in this book, you’ll need the following: • A Mac running the latest point release of OS X El Capitan or later: You’ll need this to be able to install the latest version of Xcode. • Xcode 8 or later: Xcode is the main development tool for iOS. You can download the latest version of Xcode for free on the Mac app store here: https:// itunes.apple.com/app/xcode/id497799835?mt=12 • An intermediate level knowledge of Swift and iOS development. This book is about learning RxSwift specifically; to understand the rest of the project code and how the accompanying demo projects work you will need at least an intermediate understanding of Swift and UIKit. If you want to try things out on a physical iOS device, you’ll need a developer account with Apple, which you can obtain for free. However, all the sample projects in this book will work just fine in the iOS Simulator bundled with Xcode, so the paid developer account is completely optional. Who this book is for This book is for iOS developers who already feel comfortable with iOS and Swift, and want to dive deep into development with RxSwift. If you’re a complete beginner to iOS, we suggest you first read through the latest edition of the iOS Apprentice. That will give you a solid foundation of building iOS apps with Swift from the ground up but you might still need to learn more about intermediate level iOS development before you can work through all chapters in this book. If you know the basics of iOS development but are new to Swift, we suggest you read through Swift Apprentice first, which goes through the features of Swift using playgrounds to teach the language. You can find both of these books at our online store: http://store.raywenderlich.com RxSwift - Reactive Programming with Swift Introduction raywenderlich.com 16
How to use this book Generally, each chapter in this book includes a starter project and covers a small number of programming techniques in detail. Some of the chapters deal mostly with theory so you get to try isolated pieces of code, while learning the process in a Swift playground. Other chapters provide you with a starter project that includes some non-Rx logic inside and lead you through Rx-ifying the project by adding code in key places. In the process, you’ll see what difference RxSwift makes in the project code and how to approach different common problems. We do suggest that you work through the chapters in order, since the concepts build upon each other. Remember you’ll get the most out of the book if you follow along with the tutorials and perform the hands-on challenges. For advanced developers, there’s still value in the early chapters since they cover the basics. However if you’re comfortable with those concepts, feel free to jump ahead to the topics that interest you the most. What’s in store This book is divided into six sections. You can find more details on each section in its introduction. Here’s a brief overview. Section I: Getting Started with RxSwift The first section of the book covers RxSwift basics. Don’t skip this section, as you will be required to have a good understanding of how and why things work in the following sections. Section II: Operators and Best Practices In this section, once you've mastered the basics, you will move on to building more complex Rx code by using operators. Operators allow you to chain and compose little pieces of functionality to build up complex logic. Section III: iOS Apps with RxCocoa Once you've mastered RxSwift's basics and know how to use operators, you will move on to iOS specific APIs, which will allow you to use and integrate your RxSwift code with the existing iOS classes and UI controls. RxSwift - Reactive Programming with Swift Introduction raywenderlich.com 17
Section IV: Intermediate RxSwift/RxCocoa In this section, you will look into more topics like building an error-handling strategy for your app, handling your networking needs the reactive way, writing Rx tests, and more. Section V: RxSwift Community Cookbook Many of the available RxSwift-based libraries are created and maintained by the community – people just like you. In this section, we'll look into a few of these projects and how you can use them in your own apps. Section VI: Putting it All Together This part of the book deals with app architecture and strategies for building production-quality, full-blown iOS applications. You will learn how to structure your project and explore a couple of different approaches to designing your data streams and the project navigation. Book source code and forums This book comes with complete source code for each of the chapters — it’s shipped with the PDF. Some of the chapters also include starter projects or other required resources, and you’ll definitely want to have these on hand as you go through the book. We’ve also set up an official forum for the book at raywenderlich.com/forums. This is a great place to ask questions about the book, discuss debugging strategies or to submit any errors you may find. Book updates Great news: since you purchased the PDF version of this book, you’ll receive free updates of the book’s content! The best way to receive update notifications is to sign up for our weekly newsletter. This includes a list of the tutorials published on raywenderlich.com in the past week, important news items such as book updates or new books, and a few of our favorite developer links. Sign up here: • www.raywenderlich.com/newsletter RxSwift - Reactive Programming with Swift Introduction raywenderlich.com 18
License By purchasing RxSwift: Reactive Programming in Swift, you have the following license: • You are allowed to use and/or modify the source code in RxSwift: Reactive Programming in Swift 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 RxSwift: Reactive Programming in Swift in as many apps as you want, but must include this attribution line somewhere inside your app: “Artwork/images/designs: from RxSwift: Reactive Programming in Swift book, available at http://www.raywenderlich.com.” • The source code included in RxSwift: Reactive Programming in Swift is for your personal use only. You are NOT allowed to distribute or sell the source code in RxSwift: Reactive Programming in Swift 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, co-workers or students; they would need to purchase their own copy. 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 non-infringement. 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 book are the property of their respective owners. RxSwift - Reactive Programming with Swift Introduction raywenderlich.com 19
About the cover The electric eel is a unique kind of beast. In fact, it's been reclassified few times, since it's not exactly like any other animal. It can grow to two meters in length and twenty kilograms in weight. Its size however, is not what should worry you, should you have the chance to meet one in person. That little devil sports a natural taser gun that can discharge up to 860 volts and 1 ampere of current! (Yeah, I hear you. Where was that electric eel when you were trying to jump-start your car that morning last February, right?) The electric eel was chosen for the Rx project logo since it's pre-release code name was Volta. :] Now you know! RxSwift - Reactive Programming with Swift Introduction raywenderlich.com 20