Combine Asynchronous Programming with Swift First Edition Scott Gardner 2024 Scribd Download
Combine Asynchronous Programming with Swift First Edition Scott Gardner 2024 Scribd Download
com
https://textbookfull.com/product/combine-asynchronous-
programming-with-swift-first-edition-scott-gardner/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/combine-asynchronous-programming-
with-swift-first-edition-scott-gardner-2/
textboxfull.com
https://textbookfull.com/product/rxswift-reactive-programming-with-
swift-1st-edition-florent-pillet/
textboxfull.com
https://textbookfull.com/product/asynchronous-android-programming-
helder-vasconcelos/
textboxfull.com
https://textbookfull.com/product/ios-10-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-3rd-edition-matt-neuburg/
textboxfull.com
iOS 12 Programming Fundamentals with Swift Swift Xcode and
Cocoa Basics 5th Edition Matt Neuburg
https://textbookfull.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg/
textboxfull.com
https://textbookfull.com/product/ios-11-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-4th-edition-matt-neuburg/
textboxfull.com
https://textbookfull.com/product/ios-13-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-1st-edition-matt-neuburg/
textboxfull.com
https://textbookfull.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg-2/
textboxfull.com
https://textbookfull.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg-3/
textboxfull.com
Combine | Early Access
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.
raywenderlich.com 2
Combine | Early Access
Dedications
"To Jenn, for being so supportive and encouraging. To
Charlotte, keep up the great work in school — you motivate
me! To Betty, my best l’il friend for all her 18 years. And to
you, the reader — you make this work meaningful and
fulfilling."
— Scott Gardner
— Shai Mishali
— Florent Pillet
— Marin Todorov
raywenderlich.com 3
Combine | Early Access
Shai Mishali is an author and the final pass editor on this book.
He's the iOS Tech Lead for Gett, the global on-demand mobility
company; as well as an international speaker, and a highly active
open-source contributor and maintainer on several high-profile
projects - namely, the RxSwift Community and RxSwift projects,
but also releases many open-source endeavors around Combine
such as CombineCocoa, RxCombine and more. As an avid
enthusiast of hackathons, Shai took 1st place at BattleHack Tel-
Aviv 2014, BattleHack World Finals San Jose 2014, and Ford's
Developer Challenge Tel-Aviv 2015. You can find him on GitHub
and Twitter as @freak4pc.
raywenderlich.com 4
Combine | Early Access
raywenderlich.com 5
Combine | Early Access
raywenderlich.com 6
Combine | Early Access
raywenderlich.com 7
Combine | Early Access
raywenderlich.com 8
Combine | Early Access
raywenderlich.com 9
Combine | Early Access
raywenderlich.com 10
Combine | Early Access
raywenderlich.com 11
Combine | Early Access
raywenderlich.com 12
E Early Access Edition
We hope you enjoy the preview of this book, and that you’ll come back to help us
celebrate the full launch of Combine: Asynchronous Programming with Swift later in
2019!
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 13
W What You Need
• A Mac running macOS Mojave (10.14) or later. Earlier versions might work, but
they're untested.
• Xcode 11 or later. Xcode is the main development tool for iOS. You’ll need Xcode
11 or later for the tasks in this book, since Combine was introduced with the iOS 13
SDK. You can download the latest version of Xcode from Apple’s developer site
here: apple.co/2asi58y
• An intermediate level knowledge of Swift. This book teaches you how to write
declarative and reactive iOS applications using Apple's Combine framework.
Combine uses a multitude of advanced Swift features such as generics, so you
should have at least an intermediate-level knowledge of Swift.
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 a paid
developer account is completely optional.
raywenderlich.com 14
L Book License
• You are allowed to use and/or modify the source code in Combine: Asynchronous
Programming with 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 Combine: Asynchronous Programming with Swift in as many apps as you want, but
must include this attribution line somewhere inside your app: “Artwork/images/
designs: from Combine: Asynchronous Programming with Swift, available at
www.raywenderlich.com”.
• The source code included in Combine: Asynchronous Programming with Swift is for
your personal use only. You are NOT allowed to distribute or sell the source code in
Combine: Asynchronous Programming with 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, 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 or 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 15
B Book Source Code &
Forums
• https://store.raywenderlich.com/products/combine-asynchronous-programming-
with-swift.
And if you purchased the print version of this book, you’re eligible to upgrade to the
digital editions at a significant discount! Simply email [email protected] with
your receipt for the physical copy and we’ll get you set up with the discounted digital
edition version of the book.
Forums
We’ve also set up an official forum for the book here:
• https://forums.raywenderlich.com.
This is a great place to ask questions about the book or to submit any errors you may
find.
raywenderlich.com 16
Combine | Early Access Book Source Code & Forums
Buying the digital edition version of the book also has a few extra benefits: free
updates each time we update the book, access to older versions of the book, and you
can download the digital editions from anywhere, at anytime.
• https://store.raywenderlich.com/products/combine-asynchronous-programming-
with-swift.
raywenderlich.com 17
Section I: Introduction to
Combine
In this part of the book, you're going to ramp up over the basics of Combine and
learn about some of the building blocks it comprises. You'll learn what Combine aims
to solve and what are some of the abstractions it provides to help you solve them:
Publisher, Subscriber, Subscription, Subject and much more.
raywenderlich.com 18
1 Chapter 1: Hello,
Combine!
By Marin Todorov
This book aims to introduce you to the Combine framework and to writing
declarative and reactive apps with Swift for Apple platforms.
In Apple's own words: "The Combine framework provides a declarative approach for how
your app processes events. Rather than potentially implementing multiple delegate
callbacks or completion handler closures, you can create a single processing chain for a
given event source. Each part of the chain is a Combine operator that performs a distinct
action on the elements received from the previous step."
Although very accurate and to the point, this delightful definition might sound a
little too abstract at first. That's why, before delving into coding exercises and
working on projects in the following chapters, you'll take a little time to learn a bit
about the problems Combine solves and the tools it uses to do so.
Once you've built up the relevant vocabulary and some understanding of the
framework in general, you'll move on to covering the basics while coding.
Gradually, as you progress in the book, you'll learn about more advanced topics and
eventually work through several projects.
When you've covered everything else you will, in the last chapter, work on a complete
app built with Combine.
raywenderlich.com 19
Combine | Early Access Chapter 1: Hello, Combine!
Asynchronous programming
In a simple, single-threaded language, a program executes sequentially line-by-line.
For example, in pseudocode:
begin
var name = "Tom"
print(name)
name += " Harding"
print(name)
end
Synchronous code is easy to understand and makes it especially easy to argue about
the state of your data. With a single thread of execution, you can always be sure what
the current state of your data is. In the example above, you know that the first print
will always print "Tom" and the second will always print "Tom Harding".
Now, imagine you wrote the program in a multi-threaded language that is running
an asynchronous event-driven UI framework, like an iOS app running on Swift and
UIKit.
Here, the code sets name's value to "Tom" and then adds "Harding" to it, just like
before. But because another thread could execute at the same time, it's possible that
some other part of your program could run between the two mutations of name and
set it to another value like "Billy Bob".
When the code is running concurrently on different cores, it's difficult to say which
part of the code is going to modify the shared state first.
The code running on "Thread 2" in the example above might be:
• executing at exactly the same time on a different CPU core as your original code.
raywenderlich.com 20
Combine | Early Access Chapter 1: Hello, Combine!
• executing just before name += " Harding", so instead of the original value "Tom",
it gets "Billy Bob" instead.
What exactly happens when you run this code depends on the system load, and you
might see different results each time you run the program.
Managing mutable state in your app becomes a loaded task once you run
asynchronous concurrent code.
• The delegate pattern: Lets you define an object that acts on behalf of, or in
coordination with, another object. For example, in your app delegate, you define
what should happen when a new remote notification arrives, but you have no idea
when this piece of code will be executed or how many times it will execute.
• Grand Central Dispatch and Operations: Helps you abstract the execution of
pieces of work. You can use them to schedule code to be executed sequentially in a
serial queue or to run a multitude of tasks concurrently in different queues with
different priorities.
• Closures: Create detached pieces of code that you can pass around in your code, so
other objects can decide whether to execute it, how many times, and in what
context.
Since most typical code performs some work asynchronously, and all UI events are
inherently asynchronous, it’s impossible to make assumptions about which order the
entirety of your app code will be executed.
And yet, writing good asynchronous programs is possible. It's just more complex
than... well, we'd like it to be. Unfortunately, asynchronous code and resource sharing
can produce issues which are difficult to reproduce, track down and ultimately fix.
raywenderlich.com 21
Combine | Early Access Chapter 1: Hello, Combine!
Certainly, one of the causes for these issues is the fact that a solid, real-life app most
likely uses all the different kinds of asynchronous APIs, each with its own interface,
like so:
Combine aims to introduce a new language to the Swift ecosystem that helps you
bring more order into the chaos of the asynchronous programming world.
Apple has integrated Combine's API deep into the Foundation framework, so Timer,
NotificationCenter and core frameworks like Core Data already speak its
language. Luckily, Combine is also very easy to integrate into your own code.
Finally, last but definitely not least, Apple designed their amazing new UI framework,
SwiftUI, to integrate easily with Combine as well.
raywenderlich.com 22
Combine | Early Access Chapter 1: Hello, Combine!
Various system frameworks, from Foundation all the way up to SwiftUI, depend on
Combine and offer Combine integration as an alternative to their "traditional" APIs.
Since Combine is an Apple framework, it doesn't aim to take away the role of well-
tested, solid APIs like Timer or NotificationCenter. Those Foundation types are
still present and doing their part. Instead, Combine integrates with them and allows
all the types in your app that want to talk asynchronously to each other do so via a
new, universal language.
So if the idea of using the same asynchronous tools to connect all the parts of your
app, from the data model to the networking layer and the user interface, sounds
interesting — you're in the right place, keep reading!
Foundation of Combine
Declarative, reactive programming isn't a new concept. It's been around for quite a
while, but it's made a fairly noticeable comeback in the last decade.
The first "modern-day" reactive solution came in a big way in 2009 when a team at
Microsoft launched a library called Reactive Extensions for .NET (Rx.NET).
Microsoft made that Rx.NET implementation open source in 2012, and since then,
many different languages have started to use its concepts. Currently, there are many
ports of the Rx standard like RxJS, RxKotlin, RxScala, RxPHP and more.
For Apple's platforms, there have been several third-party reactive frameworks like
RxSwift, which implements the Rx standard; ReactiveSwift, which was inspired by
raywenderlich.com 23
Combine | Early Access Chapter 1: Hello, Combine!
Combine implements a standard that is different but similar to Rx, called Reactive
Streams. Reactive Streams has a few key differences from Rx, but they both agree on
most of the core concepts.
If you haven't previously used one or another of the frameworks mentioned above —
don't worry. So far, reactive programming has been a rather niche concept for Apple's
platforms, and especially with Swift.
As with any new technology from Apple, its application is at first slightly limited:
You can use Combine only for apps that support iOS 13/macOS Catalina or later. But
as with any technology that Apple bets on, its support will quickly become
widespread and the demand for Combine skills will surge.
With that said, start by learning some of Combine's basics to see how it can help you
write safe and solid asynchronous code.
Combine basics
In broad strokes, the three key moving pieces in Combine are publishers, operators
and subscribers. There are, of course, more players in the team, but without those
three you can't achieve much.
You'll learn in detail about publishers and subscribers in Chapter 2, "Publishers and
Subscribers," and the complete second section of the book is devoted to acquainting
you with as many operators as humanly possible.
In this introductory chapter, however, you're going to get a simple crash course to
give you a general idea of the purpose those types have in the code and what their
responsibilities are.
Publishers
Publishers are types that can emit values over time to one or more interested parties,
such as subscribers. Regardless of the internal logic of the publisher, which can be
pretty much anything including math calculations, networking or handling user
events, every publisher can emit multiple events of these three types:
raywenderlich.com 24
Combine | Early Access Chapter 1: Hello, Combine!
2. A successful completion.
A publisher can emit zero or more output values, and if it ever completes, either
successfully or due to a failure, it will not emit any other events.
Here's how a publisher emitting Int values could look like visualized on a timeline:
The blue boxes represent values that are emitted at a given time on the timeline, and
the numbers represent the emitted values. A vertical line, like the one you see on the
right-hand side of the diagram, represents a successful stream completion.
The simple contract of three possible events is so universal that it could represent
any kind of dynamic data in your program. That's why you can address any task in
your app using Combine publishers — regardless of whether it's about crunching
numbers, making network calls, reacting to user gestures or displaying data on-
screen.
Instead of always looking in your toolbox for the right tool to grab for the task at
hand, be it adding a delegate or injecting a completion callback — you can just use a
publisher instead.
One of the best features of publishers is that they come with error handling built in;
error handling isn't something you add optionally at the end, if you feel like it.
The Publisher protocol is generic over two types, as you might have noticed in the
diagram earlier:
raywenderlich.com 25
Combine | Early Access Chapter 1: Hello, Combine!
• Publisher.Failure is the type of error the publisher can throw if it fails. If the
publisher can never fail, you specify that by using a Never failure type.
When you subscribe to a given publisher, you know what values to expect from it and
which errors it could fail with.
Operators
Operators are methods declared on the Publisher protocol that return either the
same or a new publisher. That's very useful because you can call a bunch of operators
one after the other, effectively chaining them together.
Because these methods, called "operators", are highly decoupled and composable,
they can be combined (aha!) to implement very complex logic over the execution of a
single subscription.
It's fascinating how operators fit tightly together like puzzle pieces. They cannot be
mistakenly put in the wrong order or fit together if one's output doesn't match the
next one's input type:
In a clear deterministic way, you can define the order of each of those asynchronous
abstracted pieces of work alongside with the correct input/output types and built-in
error handling. It's almost too good to be true!
As an added bonus, operators always have input and output, commonly referred to as
upstream and downstream — this allows them to avoid shared state (one of the
core issues we discussed earlier). Operators focus on working with the data they
receive from the previous operator and provide their output to the next one in the
chain. This means that no other asynchronously-running piece of code can "jump in"
and change the data you're working on.
raywenderlich.com 26
Combine | Early Access Chapter 1: Hello, Combine!
Subscribers
Finally, you arrive at the end of the subscription chain: Every subscription ends with
a subscriber. Subscribers generally do "something" with the emitted output or
completion events.
Currently, Combine provides two built-in subscribers, which make working with data
streams straightforward:
• The sink subscriber allows you to provide closures with your code that will receive
output values and completions. From there, you can do anything your heart desires
with the received events.
• The assign subscriber allows you to, without the need of custom code, bind the
resulting output to some property on your data model or on a UI control to display
the data directly on-screen via a key path.
Should you have other needs for your data, creating custom subscribers is even easier
than creating publishers. Combine uses a set of very simple protocols that allow you
to be able to build your own custom tools whenever the workshop doesn't offer the
right one for your task.
raywenderlich.com 27
Combine | Early Access Chapter 1: Hello, Combine!
Subscriptions
Note: This book uses the term subscription to describe both Combine’s
Subscription protocol and its conforming objects, as well as the complete
chain of a publisher, operators and a subscriber.
When you add a subscriber at the end of a subscription, it "activates" the publisher all
the way at the beginning of the chain. This is a curious but important detail to
remember — publishers do not emit any values if there are no subscribers to
potentially receive the output.
Subscriptions are a wonderful concept in that they allow you to declare a chain of
asynchronous events with their own custom code and error handling only once, and
then you never have to think about it again.
If you go full-Combine, you could describe your whole app's logic via subscriptions
and once done, just let the system run everything without the need to push or pull
data or call back this or that other object:
Once the subscription code compiles successfully and there are no logic issues in
your custom code — you're done! The subscriptions, as designed, will asynchronously
"fire" each time some event like a user gesture, a timer going off or something else
awakes one of your publishers.
Even better, you don't need to specifically memory manage a subscription, thanks to
a protocol provided by Combine called Cancellable.
raywenderlich.com 28
Combine | Early Access Chapter 1: Hello, Combine!
This means you can easily "bind" the lifespan of a subscription by storing it in a
property on your view controller, for example. This way, any time the user dismisses
the view controller from the view stack, that will deinitialize its properties and will
also cancel your subscription.
As you see, there's plenty to learn, but it's all logical when explained in detail. And
that's exactly what the plan is for the next chapters — to bring you slowly but steadily
from zero to Combine hero by the end of this book.
Combine (and other system frameworks) aims to add another abstraction in your
async code. Another level of abstraction on the system level means tighter
integration that's well tested and a safe-bet technology for long-lasting support.
It's up to you to decide whether Combine is a great fit for your project or not, but
here are just a few "pro" reasons you might not have considered yet:
• Combine is integrated on the system level. That means Combine itself uses
language features that are not publicly available, offering you APIs that you
couldn't build yourself.
• The "old" style async code via delegates, IBAction or closures pushes you towards
writing custom code for each case of a button or a gesture you need to handle.
That's a lot of custom code to write tests for. Combine abstracts all async
operations in your code as "operators", which are already well tested.
raywenderlich.com 29
Discovering Diverse Content Through
Random Scribd Documents
Nitrogenous Foodstuffs or Proteins
The proteins form heat and energy when the supply of sugars,
starches, and fat are exhausted, but proteins, alone form muscle,
bone and sinew. They are, in this sense, the most important of foods,
—they are, also, the most costly.
The foods most rich in proteins are meat and eggs. These have
undergone chemical changes from the vegetable kingdom being built
up into more complex compounds in the animal kingdom.
Meat and eggs are the tissue builders. In this connection it may be
well to state that blood is tissue; thus meat and eggs build the blood,
as well as muscle and sinew.
Nitrogenous foods, or proteins, are so called because of the large
proportion of nitrogen which they contain. All nitrogenous foods
contain considerable carbon—mostly in the form of fat in the meat
elements—but the carbonaceous foods contain so little of the
proteins that they do not appreciably enter into the nutrition,—the
carbon and nitrogen in the carbo-nitrogenous foods are more equally
divided.
The nitrogenous or protein elements in the body constitute about
one-fifth of its weight. They make the framework, forming the basis
of blood, lymph, muscle, sinew, bone, skin, cartilage, and other
tissues.
Worn out body tissues is constantly being torn down and
eliminated and the protein in the foods must daily furnish material for
repair, as well as for building new tissue in the growing child.
A young animal’s first need is for growth, not having learned to
exercise sufficiently to use much energy, and the first food given is
an animal product—milk to babes and other mammals, while the
young of other animals are first fed upon eggs.
The nitrogenous foods are required in smaller bulk than
vegetables and fruits; they are more concentrated and contain less
waste. According to recent experiments, the average adult requires
from two to four ounces a day of nitrogenous foods, to repair the
waste, according to the proportion of nitrogen contained. Happily,
where more is consumed, the system has the power, up to a certain
limit (depending upon the physical condition and the daily activity), to
eliminate an excess. It is needless to say that if the daily waste is not
re-supplied, the digestion and bodily nutrition suffer. The system
must have the two to four ounces to supply the nitrogen daily
excreted, or the tissues themselves will be consumed.
The proteins, of which meat is the principal one, are classified as
Albuminoids:—albumin (white of eggs), casein (curd of milk),
myosin (the basis of lean meat and gluten of wheat),
Gelatinoids, (connective tissue of meat),
Extractives (appetizing and flavoring elements).
DIGESTION
Any discussion in regard to the digestibility of foods must be
general, because food which agrees with one may disagree with
another, and a food which disagrees with one at a particular time
may entirely agree with him at some other time; therefore, before
one passes upon the adaptability of a food to the individual, it should
be known that this food agrees or disagrees with him under varying
conditions.
The digestibility of food depends largely upon the physical
condition of the individual, because the amount of digestive juices
poured into the alimentary canal is influenced by this condition,
particularly by the condition of the nerves. If sufficient juices, in
proper proportions, are not poured into the digestive tract, the
foodstuffs are not made soluble for absorption into the blood.
Digestion is practically synonymous with solution,—all solid foods
must be reduced to a liquid state, through digestive juices and water,
before they can pass through the walls of the stomach and
intestines.
Each individual should learn to like the foods containing the
nutrient elements which experience and blood tests have shown to
be lacking in his case. The question of likes and of dislikes in regard
to foods, is largely habit, and one can learn to like almost any food
one wishes.
Where one forms the habit of discriminating too much in the food,
or discarding this food or that, because at some time it has
disagreed, due to the particular condition at the time, the mind
approaches the table as a more or less pessimistic censor and the
saliva and the gastric juices are retarded in their flow.
When one is exercising freely, so that the muscular and mucous
coats of the digestive system are strong, the body will handle foods
which, during sedentary habits, it would not digest. There are kinds
of foods, however, which, to certain individuals, according to the
chemical composition of the body, act as actual poisons, e. g.,
strawberries, cheese, or coffee.
It may be well to here trace, briefly, the progress of the food
through the digestive tract and the action of the juices and the
ferments upon it.[3]
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com