35,99 €
Learn how to solve blocking user experience and build event based reactive applications with Swift.
RxSwift belongs to a large family of Rx
implementations in different programming
languages that share almost identical syntax
and semantics. Reactive approach will
help you to write clean, cohesive, resilient,
scalable, and maintainable code with highly
configurable behavior.
This book will introduce you to the world of
reactive programming, primarily focusing
on mobile platforms. It will tell how you can
benefit from using RxSwift in your projects,
existing or new. Further on, the book will
demonstrate the unbelievable ease of
configuring asynchronous behavior and
other aspects of the app that are traditionally
considered to be hard to implement and
maintain. It will explain what Rx is made
of, and how to switch to reactive way of
thinking to get the most out of it. Also, test
production code using RxTest and the red/
green approach. Finally, the book will dive
into real-world recipes and show you how
to build a real-world app by applying the
reactive paradigm.
By the end of the book, you’ll be able to build
a reactive swift application by leveraging all
the concepts this book takes you through.
This book is for the developers who are familiar with Swift and iOS application development and are looking out to reduce the complexity of their apps. Prior experience of reactive programming is not necessary.
Navdeep Singh is a result-oriented software developer and research professional with more than 7 years of experience in both development and research positions. He strives to create software with the user in mind, creating applications with a usable and intuitive user interface experience. Navdeep spends most of his time learning about the latest trends in technology, writing blogs, playing cricket, or practicing classical Hindustani music.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 305
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudhariAcquisition Editor: Isha RavalContent Development Editor: Flavian VazTechnical Editor: Akhil NairCopy Editor: Shaila KusanaleProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Rekha NairGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai
First published: February 2018
Production reference: 1210218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78712-021-1
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Navdeep Singh is a result-oriented software developer and research professional with more than 7 years of experience in both development and research positions. He strives to create software with the user in mind, creating applications with a usable and intuitive user interface experience. Navdeep spends most of his time learning about the latest trends in technology, writing blogs, playing cricket, or practicing classical Hindustani music.
Kevin Munc (@muncman) is a 20-year programming veteran with wide experience, from mainframes to mobile. Along the way, he's reviewed books on Objective-C, watchOS, UIAutomation, Sprite Kit, JavaFX, and Vim.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Reactive Programming with Swift 4
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Migrating from Swift 3 to Swift 4
What's new in Swift 4?
Setting up the environment
What’s changed?
Changes/improvements in Dictionary
Grouping initializer
Key-based subscript with default value
Convert tuples to Dictionary
Convert arrays to Dictionary
Resolving duplicates
Reserving capacity
Changes/improvements in Strings
Bid bye to string.characters
String protocol
Changed interpretation of grapheme clusters
Access modifiers
What's new
JSON encoding and decoding
Multiline String literals
Smart key paths
One sided ranges
Pattern matching with one sided ranges.
swap versus swapAt
Improved NSNumber
Directly access unicode scalars of characters
Migrating to Swift 4
Preparation before migration
Swift migration assistant
Swift 4 migration changes overview
SDK changes
Notable special cases
New String
Differentiating between single-tuple and multiple-argument function types
Adding tuple destructuring
Default parameter values must be public
After migration
Known migration issues
Using Carthage/CocoaPods projects
Summary
FRP Fundamentals, Terminology, and Basic Building Blocks
Functional reactive programming
What is functional reactive programming (FRP)?
Imperative programming
Functional programming
Reactive programming
Basic building blocks
Event streams
State
Side effects
Immutability
RxSwift foundation
Reactive extensions
Observable
Subject
Marble diagrams
Schedulers
Railway-oriented programming
Summary
Set up RxSwift and Convert a Basic Login App to its RxSwift Counterpart
RxSwift in action
Let's build the environment first
Setting up the environment
RxSwift with CocoaPods
Installing RxSwift
Installing RxSwift with Carthage
Let's get started – The Login page
Setting up
Steps to set up
Functional programming to the rescue
Summary
When to Become Reactive?
Creating and subscribing to Observables
Project setup
Getting started
Different types of subject
PublishSubject in action
BehaviorSubject in action
ReplaySubject in action
Variable in action
Understanding traits and its types
What are traits?
Different types of trait
The single trait
The completable trait
The maybe trait
Summary
Filter, Transform, and Simplify
Working with events using operators
Environment setup
Transforming operators
flatMap and flatMapLatest in action
Scan, reduce, and buffer
Scan
Buffer
Filtering operators
The filter operator
The distinctUntilChanged operator
The takeWhile operator
Summary
Reduce by Combining and Filtering and Common Trade Offs
Combining and filtering Observable sequences
Project setup
Concatenating and prefixing
Merging
Combining elements of different types
Introducing zip
Performing side effects
doOn in action
Setting the project
Building the app
Summary
React to UI Events – Start Subscribing
RxCocoa traits
Types of RxCocoa traits
Driver
ControlProperty
ControlEvent
Binding UI elements in practice
Binding data to UI
Binding UITableViews
Configuring cell rows in a TableView
Selecting a row in TableView
Binding UICollectionViews
Summary
RxTest and Custom Rx Extensions – Testing with Rx
Testing in RxSwift
RxTest
Testing in practice with HotObservables
Testing in RxTest with ColdObservables
RxBlocking
Testing with RxBlocking
Summary
Testing Your RxCode – Testing Asynchronous Code
Tracking down issues – Debugging Rx code
Debugging with debug
Debugging with total
Testing asynchronous code
Summary
Schedule Your Tasks, Don't Queue!
Queues and schedulers
Scheduler Singletons
Specifying a scheduler
Schedulers in practice
ConcurrentDispatchQueueScheduler
SerialDispatchQueueScheduler
OperationQueueScheduler
Summary
Subscribe to Errors and Save Your App
Error handling
The catchErrorJustReturn operator
The catchError operator
The retry operator
onErrorJustReturn
onErrorDriveWith
onErrorRecover
Summary
Functional and Reactive App-Architecture
Design patterns
Singleton design pattern
Implementation
Singleton design pattern – Pros and cons
Key value coding (KVC)
KVC – Implementation
Notifications
Notifications – Implementation
Model view controller – MVC
The model
The view
The controller
MVC implementation
Summary
Finish a Real-World Application
Networking in RxSwift
Project setup
Project implementation
Fetching and parsing data
Binding fetched data to View elements
Build and run
Some other cool libraries
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
As a platform, iOS offers numerous APIs to write asynchronous code and, many a times, this choice becomes hard to manage and a single code base ends up comprising multiple Asynchronous API usages, for example, closures for small Async tasks, delegation for background tasks, notification center for event-based tasks, and such. Managing and modifying such a code base might become a headache even if it is written in the best way possible, and the problem becomes more severe if a big team is involved with a single code base.RxSwiftbrings in uniformity so that different types of requirements (mentioned earlier) are handled withRxSwiftcode and hence you, as a developer, get more control over the processes and different module interactions within the app.
The main mission of this book is to give you a platform to catapult your skills to be on par with the best RxSwift developers out there. Follow the content in the book as per the schedule, and rest assured that you will achieve the mission.
This book is for iOS developers who have intermediate knowledge of Swift development for IOS and want to take their skill set to the next level. RxSwift offers more control over asynchronous code in your iOS environment, and, as a seasoned developer, even a slight advantage to the way asynchronous code is written is always welcome. This book will challenge the way you have been thinking about your apps' logic and guide you along the way as you turn the tables and start thinking in a more declarative way as compared to the traditional imperative way. In short, you will learn how to think in “what to do” terminology as compared to “how to do.”
For those who are eager to become a Swift Ninja, this book aims to work in a slightly unique manner—we will dive straight into the code, and as we build on the demo applications, we will explain the concepts “on the fly,” as they say! Development is all about practice, and this book abides by that rule right from the word go.
Chapter 1, Migrating from Swift 3 to Swift 4, teaches what’s new in Swift 4 and how you can transition your code from Swift 3 to Swift 4. Unlike the previous Swift releases, this time the conversion is more seamless, and you will see this in practice with the help of an example.
Chapter 2, FRP Fundamentals, Terminology, and Basic Building Blocks, takes you through FRP and its basic building blocks, marble diagrams, and sequence diagrams to understand more about sequences and events in brief. Finally, the chapter will unleash Railway-oriented programming and a brief introduction on error handling in FRP. You will learn how you can handle errors in one single place without having to care about handling errors at every single event.
Chapter 3, Set up RxSwift and Convert a Basic Login App to its RxSwift Counterpart, explains that the best way to get the feel about any topic is practice. This chapter will take a nosedive into the RxSwift world by converting an existing Swift app into RxSwift. You will see the RxSwift syntax for the very first time in this chapter and get to work with a real-world application.
You will get a feel of how to convert an existing code base into a RxSwift code base and compare the benefits of the newly learned reactive concepts.
You will note the increased readability and concise but clear code that can be written using the RxSwift library when compared to normal Swift. The gist of this chapter is to provide you with a comparison to understand the benefits that RxSwift code brings into play.
Chapter 4, When to become Reactive?, helps you to use your armor judiciously, as it might lead to increased complexity if not used in a proper setting. When writing any code, keep in mind that the best code might not be the smartest code out there, rather, the best code is the one that is easier to maintain and understand. This chapter will brief you about when to use RxSwift in your application. You will also work with playgrounds to understand some more core concepts that enable you to simplify your complex code base.
Chapter 5, Filter, Transform, and Simplify, along with the next chapter, teaches you how to apply operators to filter out events and then proceed to handle them. You will play with major building blocks of RxSwift and note the clarity and control that you get as compared to normal Swift code while dealing with event-driven concepts. In this chapter, you will work with Playgrounds to transform sequences by filtering them using map, flatmap, and other such operators as they are generated so that you can take respective actions as per the type of the event that is generated.
Chapter 6, Reduce by Combining and Filtering and Common Trade Offs, might sound tedious to read at first, but the concepts will get more clear as we practice with real examples. In this chapter, you will work with some more transforming operators to reduce the observable data stream by making use of combining and filtering operators in conjunction and then gradually work your way to know other operators, such as mathematical and time based.
You will also read about the trade-offs while incorporating these operators in your code so that you can be careful while making the choice to go reactive.
Chapter 7, React to UI Events – Start Subscribing, introduces you to another framework, which is part of the original RxSwift repository—RxCocoa.
Convert your simple UI elements such as UIButtons and UITextFields to Reactive components. You will learn how to subscribe to events emitted by your newly created reactive UI components and perform respective actions depending on the type of the event. For instance, a UIButton might have a touchUpInside or long press event, and you might want to respond to both the events differently.
This chapter will also introduce you to some reactive networking code and how you can subscribe to events while your code is interacting with API calls.
Chapter 8, RxTest and Custom Rx Extensions – Testing with Rx, discusses RxTest, and later, RxBlocking, by writing tests against several RxSwift operations and also writing tests against production RxSwift code. Also, you will create an extension to NSURLSession to manage the communication with an endpoint.
Chapter 9, Testing Your RxCode – Testing Asynchronous Code, says that almost every IOS app needs some sort of API access to fetch or save data over cloud to complete its workflow and hence it becomes important to test code that interacts with APIs. Since response from APIs is uncertain and error prone, the code that interacts with APIs should be tested rigorously before shipping with production code. This chapter introduces you to concepts such as mocking, stubbing, dependency injections, and expectations and sheds some light on how you can substitute your live APIs with dummy data.
You will also know how to continue development even when your API is not ready and, as a result, fasten your sprints.
Chapter 10, Schedule Your Tasks, Don't Queue!, informs that in traditional Swift, there are different ways to handle concurrency—GCD, Operational Queues, and so on. This chapter introduces you to the concept of schedulers. RxSwift encourages a developer not to work directly with locks or queues, and 99% of the times, you will be encouraged to use platform-provided schedulers rather than creating custom schedulers.
Chapter 11, Subscribe to Errors and Save Your App, describes that it does not take long for negative inputs to pour in when an app with users in production shuts down abruptly. This chapter will cover the beauty behind error handling in RxSwift. You can subscribe to errors and react to different types of errors either in one way or follow a specific path for specific errors, for instance, retrying if a download failed abruptly, reauthenticating a user behind the scenes if the session has expired, and so on.
Chapter 12, Functional and Reactive App-Architecture, compares different design patterns that can be used while writing RxSwift apps from scratch or modifying current apps to incorporate Reactive and functional behavior. You will know about observation, iteration, delegation, MVC, and MVVM and try to figure out which design pattern fits the puzzle in the best way possible. This chapter will also introduce you to different open source APIs that can be incorporated to your ongoing projects.
Chapter 13, Finish a Real-World Application, concludes that you would have covered a lot so far and worked on a lot of code examples; now, you will put everything that you have learned so far to practice in one place and finish an app that we started earlier in Chapter 2, FRP Fundamentals, Terminology, and Basic Building Blocks. This chapter will cover the MVVM application architecture and show how a well-designed ViewModel can power an RxSwift app.
We assume that you, the reader of this book, already have intermediate knowledge of Swift programming language and have worked on iOS applications before.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Reactive-Swift-4-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/ReactiveProgrammingwithSwift4_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Setting up an RxSwift environment"
A block of code is set as follows:
use_frameworks!target 'YOUR_TARGET_NAME' dopod 'RxSwift'pod 'RxCocoa'end
Any command-line input or output is written as follows:
sudo gem install cocoapods
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Now pick the recently installed Swift 4.0 Snapshot and restart Xcode IDE"
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
This book aims to build on your current iOS development knowledge in Swift and gradually increase your Swift skills to master Reactive programming concepts in Swift. This book will guide you through the concepts while working with real-world apps and projects to give you a better understanding of RxSwift and related APIs.
Swift, as a programming language, has evolved many times over the years since its launch in 2014, and like any software update, we developers have to keep ourselves updated as well. We will start this book by giving you a hands-on update about what's new in Swift and how you can seamlessly migrate from your Swift 3 code to the latest Swift 4 syntax. You will then learn about Swift 4's new features and enhancements—from improvements in language syntax to the new protocols and APIs.
We will start with compatible Xcode IDE and how you can set up the environment required to work with the latest Swift release, some prerequisites before starting to migrate to the latest version, premigration preparation, things to do once the migration is complete, special cases, and other related stuff as we go through this chapter.
Unlike previous Swift releases, this release provides source compatibility with Swift 3 while working toward ABI stability. The main topics that will be covered in this chapter are as listed:
Setting up the Swift 4 environment
Changes/improvements to Swift
Additions to Swift
Migrating to Swift 4
Swift 4 includes many changes; 21 proposals have been implemented to be specific, but we will only cover a subset of those. Around 10 of these relate to the Swift package manager and of the remaining 11, some of the changes are minor improvements, so we will cover the ones that you will encounter in your day-to-day work.
There are a couple of ways to run Swift 4.
It's a prerequisite that you have a developer account and then you can use either of the mentioned methods:
Install Xcode 9, search for Xcode 9, log in with your developer account, and download the current beta available for downloads.
In case you prefer to use Xcode 8, you can use the latest development snapshot for Swift 4.0 available at
Swift.org
. Once the download finishes, open the package
.pkg
file and install the snapshot. Open
Xcode
and go to
Xcode
|
Toolchains
|
Manage Toolchains
. Now pick the recently installed
Swift 4.0 Snapshot
and restart
Xcode IDE
:
Now your projects or playgrounds will use Swift 4 while compiling. We will use Xcode 9 for writing and executing all the code in this book. At the time of writing, the current Xcode 9 is in beta release version 6.
In the subsequent sections, you will read about the new features available in Swift 4, how you can transition to the latest Swift version, that is, Swift 4, and what should be the strategy for switching a massive code base written in Swift 3 to Swift 4; however, before that, a word of caution- the language is still in beta, and we should expect some changes and bug fixes along the lines until the official release is announced. With that being said, there is nothing to worry about; to keep an eye on the changes and stay up to date with the new implementations and bug fixes, follow the official release notes.
Before we go ahead and discuss the new additions, let’s see what has changed or improved in the existing language.
Dictionary and sequence now have the capacity to explicitly, unambiguously reserve capacity.
Suppose you have a sequence of friends with an initial capacity of 4:
friends.capacity // 4
You can now reserve the capacity by doing this:
friends.reserveCapacity(20)
This reserves a minimum of 20 segments of capacity:
friends.capacity // 20
Reallocating memory to objects can be an expensive task, and if you have an idea about how much space it will require to store an object, then using reserveCapacity(_:) can be an easy and simple way to increase performance.
Swift 4 brings in a number of modifications to the Dictionary, 12 to be exact as per the official Apple developers guide, and a number of additions that we will discuss in subsequent sections:
Undoubtedly, the String is one of the majorly used data types in all the programming languages. Apparently, it is the data type that mankind understands better. Strings are important to the extent that they have the ability to significantly change our perception of how difficult or simple it is to learn a programming language. Hence, it becomes really important to follow any development to this data type. Strings received a major overhaul with Swift 4, making them collections of characters. In the earlier versions, several times, Swift, with its complicated way of handling subStrings and characters, went overboard in advocating accuracy over convenience.
