100% found this document useful (4 votes)
25 views

Combine Asynchronous Programming with Swift First Edition Scott Gardner 2024 Scribd Download

First

Uploaded by

jfroffa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
25 views

Combine Asynchronous Programming with Swift First Edition Scott Gardner 2024 Scribd Download

First

Uploaded by

jfroffa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Combine Asynchronous Programming with Swift First


Edition Scott Gardner

https://textbookfull.com/product/combine-asynchronous-
programming-with-swift-first-edition-scott-gardner/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Combine Asynchronous Programming with Swift First Edition


Scott Gardner

https://textbookfull.com/product/combine-asynchronous-programming-
with-swift-first-edition-scott-gardner-2/

textboxfull.com

RxSwift Reactive Programming with Swift 1st Edition


Florent Pillet

https://textbookfull.com/product/rxswift-reactive-programming-with-
swift-1st-edition-florent-pillet/

textboxfull.com

Asynchronous Android Programming Helder Vasconcelos

https://textbookfull.com/product/asynchronous-android-programming-
helder-vasconcelos/

textboxfull.com

iOS 10 Programming Fundamentals with Swift Swift Xcode and


Cocoa Basics 3rd Edition Matt Neuburg

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

iOS 11 Programming Fundamentals with Swift Swift Xcode and


Cocoa Basics 4th Edition Matt Neuburg

https://textbookfull.com/product/ios-11-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-4th-edition-matt-neuburg/

textboxfull.com

iOS 13 Programming Fundamentals with Swift Swift Xcode and


Cocoa Basics 1st Edition Matt Neuburg

https://textbookfull.com/product/ios-13-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-1st-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-2/

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-3/

textboxfull.com
Combine | Early Access

Combine: Asynchronous Programming with


Swift
By Scott Gardner, Shai Mishali, Florent Pillet & Marin Todorov

Copyright ©2019 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.

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

"For my wife Elia and Baby Ethan—my love, inspiration, and


rock ❤ . To my family and friends for their support: Dad,
Mom, Ziv, Adam, and everyone else, you’re the best!"

— Shai Mishali

"To Fabienne and Alexandra ❤ ."

— Florent Pillet

"To my father. To my mom. To Mirjam and our beautiful


daughter."

— Marin Todorov

raywenderlich.com 3
Combine | Early Access

About the Authors


Scott Gardner is an author and the technical editor for this book.
Combined, he’s authored over a dozen books, video courses,
tutorials, and articles on Swift and iOS app development — with a
focus on reactive programming. He’s also presented at numerous
conferences. Additionally, Scott teaches app development and is an
Apple Certified Trainer for Swift and iOS. Scott has been
developing iOS apps since 2010, ranging from personal apps that
have won awards to working on enterprise teams developing apps
that serve millions of users. You can find Scott on Twitter or
GitHub as @scotteg or connect with him on LinkedIn at
scotteg.com.

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.

Florent Pillet is an author of this book. He 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,
using it in production since 2015. A freelance developer, Florent
also uses reactive programming on the server side as well as on
Android and likes working on tools for developers like the popular
NSLogger when he's not contracting, training or reviewing code for
clients worldwide. Say hello to Florent on Twitter and GitHub at
@fpillet.

raywenderlich.com 4
Combine | Early Access

Marin Todorov is an author of this book. Marin is one of the


founding members of the raywenderlich.com team and has worked
on eight of the team’s books. He's an independent contractor and
has worked for clients like Roche, Realm, and others. 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.

About the Artist


Vicki Wenderlich is the designer and artist of the cover of this
book. She is Ray’s wife and business partner. She is a digital artist
who creates illustrations, game art and a lot of other art or design
work for the tutorials and books on raywenderlich.com. When she’s
not making art, she loves hiking, a good glass of wine and
attempting to create the perfect cheese plate.

raywenderlich.com 5
Combine | Early Access

Table of Contents: Overview


Early Access Edition............................................................................... 13
What You Need ........................................................................................ 14
Book License ............................................................................................. 15
Book Source Code & Forums ............................................................. 16
Section I: Introduction to Combine .............................. 18
Chapter 1: Hello, Combine! .................................................... 19
Chapter 2: Publishers & Subscribers .................................. 35
Section II: Operators ......................................................... 65
Chapter 3: Transforming Operators ................................... 67
Chapter 4: Filtering Operators ............................................. 88
Chapter 5: Combining Operators ...................................... 111
Chapter 6: Time Manipulation Operators ..................... 136
Chapter 7: Sequence Operators ........................................ 161
Chapter 8: In Practice: Project "Collage"........................ 182
Section III: Combine in Practice .................................. 207
Chapter 9: Combine for Networking ............................... 209
Chapter 10: Debugging Combine ...................................... 215
Chapter 11: Combine Timers .............................................. 220
Chapter 12: Key-Value Observing .................................... 225
Chapter 13: Resources in Combine .................................. 232
Chapter 14: In Practice: Project "News" ........................ 239

raywenderlich.com 6
Combine | Early Access

Section IV: Advanced Combine ................................... 257


Section V: Building a Complete App .......................... 259
Conclusion .............................................................................................. 260

raywenderlich.com 7
Combine | Early Access

Table of Contents: Extended


Early Access Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
What You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Book License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Book Source Code & Forums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Section I: Introduction to Combine . . . . . . . . . . . . . . . . 18
Chapter 1: Hello, Combine! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Asynchronous programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Foundation of Combine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Combine basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
What's the benefit of Combine code over "standard" code? . . . . . . . . . 29
App architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Book projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Chapter 2: Publishers & Subscribers. . . . . . . . . . . . . . . . . . . . . . . . . 35
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Hello Publisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Hello Subscriber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Hello Cancellable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Understanding what’s going on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Creating a custom subscriber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Hello Future . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Hello Subject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Dynamically adjusting demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Type erasure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

raywenderlich.com 8
Combine | Early Access

Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Section II: Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65


Chapter 3: Transforming Operators . . . . . . . . . . . . . . . . . . . . . . . . . 67
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Collecting values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Mapping values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Flattening publishers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Replacing upstream output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Incrementally transforming output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Chapter 4: Filtering Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Filtering basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Compacting and ignoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Finding values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Dropping values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Limiting values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Chapter 5: Combining Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Prepending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Appending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Advanced combining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

raywenderlich.com 9
Combine | Early Access

Chapter 6: Time Manipulation Operators . . . . . . . . . . . . . . . . . . 136


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Shifting time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Collecting values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Collecting values (part 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Holding off on events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Timing out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Measuring time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Chapter 7: Sequence Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Finding values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Querying the publisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Chapter 8: In Practice: Project "Collage" . . . . . . . . . . . . . . . . . . . 182
Getting started with "Collage" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Talking to other view controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Wrapping a callback function as a future . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Presenting a view controller as a future. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Sharing subscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Publishing properties with @Published . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Operators in practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206

Section III: Combine in Practice. . . . . . . . . . . . . . . . . . . 207


Chapter 9: Combine for Networking . . . . . . . . . . . . . . . . . . . . . . . 209

raywenderlich.com 10
Combine | Early Access

URLSession extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209


Codable support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Publishing network data to multiple subscribers . . . . . . . . . . . . . . . . . . . 211
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Chapter 10: Debugging Combine . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Printing events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Acting on events — performing side effects . . . . . . . . . . . . . . . . . . . . . . . . . 217
Using the debugger as a last resort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Chapter 11: Combine Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Using RunLoop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Using the Timer class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Using DispatchQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Chapter 12: Key-Value Observing . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Introducing publisher(for:options:) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Preparing and subscribing to your own KVO-compliant properties 226
ObservableObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Chapter 13: Resources in Combine . . . . . . . . . . . . . . . . . . . . . . . . 232
The share() operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
The multicast(_:) operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Future . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Chapter 14: In Practice: Project "News" . . . . . . . . . . . . . . . . . . . 239

raywenderlich.com 11
Combine | Early Access

Getting started with the Hacker News API . . . . . . . . . . . . . . . . . . . . . . . . . 240


Getting a single story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Multiple stories via merging publishers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Getting the latest stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255

Section IV: Advanced Combine . . . . . . . . . . . . . . . . . . . 257


Section V: Building a Complete App . . . . . . . . . . . . . . 259
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260

raywenderlich.com 12
E Early Access Edition

You’re reading an early access edition of Combine: Asynchronous Programming with


Swift. This edition contains a sample of the chapters that will be contained in the
final release.

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

To follow along with this book, you’ll need the following:

• 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

By purchasing Combine: Asynchronous Programming with Swift, you have the


following 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

If you bought the digital edition


This book comes with the source code for the starter and completed projects for each
chapter. These resources are shipped with the digital edition you downloaded here:

• https://store.raywenderlich.com/products/combine-asynchronous-programming-
with-swift.

If you bought the print version


You can get the source code for the print edition of the book here: https://
store.raywenderlich.com/products/combine-asynchronous-programming-with-
swift-source-code.

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

Digital book editions


We have a digital edition of this book available in both ePUB and PDF, which can be
handy if you want a soft copy to take with you, or you want to quickly search for a
specific term within the book.

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.

Visit our book store page here:

• 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.

Specifically, you'll cover:

Chapter 1: Hello Combine: A gentle introduction to what kind of problems


Combine solves, a back story of the roots of reactive programming on Apple's
platforms, and a crash course into the basic moving pieces of the framework.

Chapter 2: Publishers & Subscribers: The essence of Combine is that publishers


send values to subscribers. In this chapter you’ll learn all about what that means and
how to work with publishers and subscribers, and how to manage the subscriptions
that are created between the two of them.

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.

Consider what could potentially happen:

--- Thread 1 ---


begin
var name = "Tom"
print(name)

--- Thread 2 ---


name = "Billy Bob"

--- Thread 1 ---


name += " Harding"
print(name)
end

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.

Foundation and UIKit/AppKit


Apple has been improving asynchronous programming for their platforms over the
years. They've created several mechanisms you can use, on different system levels, to
create and execute asynchronous code. You’ve probably used these in your projects
without giving them a second thought because they are so fundamental to writing
mobile apps.

You’ve probably used most of the following:

• NotificationCenter: Executes a piece of code any time an event of interest


happens, such as when the user changes the orientation of the device or when the
software keyboard shows or hides on the screen.

• 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.

To give you an idea of how committed Apple is to reactive programming with


Combine, here's a simple diagram showing where Combine sits in the system
hierarchy:

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!

Rx; Interstellar, which is a custom implementation and others.

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.

In iOS 13/macOS Catalina, however, Apple brought reactive programming support to


its ecosystem via the built-in system framework, Combine.

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:

1. An output value of the publisher's generic Output type.

raywenderlich.com 24
Combine | Early Access Chapter 1: Hello, Combine!

2. A successful completion.

3. A completion with an error of the publisher's Failure type.

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:

• Publisher.Output is the type of the output values of the publisher. If the


publisher is specialized as an Int, it can never emit a String or a Date value.

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!

Both system-provided subscribers conform to Cancellable, which means that your


subscription code (e.g. the whole publisher, operators and subscriber call chain)
returns a Cancellable object. Whenever you release that object from memory, it
cancels the whole subscription and releases its resources from memory.

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.

Or to automate this process, you can just have an [AnyCancellable] collection


property on your type and throw as many subscriptions inside it as you want. They'll
all be automatically canceled and released when the property is released from
memory.

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.

What's the benefit of Combine code over


"standard" code?
You can, by all means, never use Combine and still create the best apps out there.
There's no argument about that. You can also create the best apps without Core Data,
URLSession, or even UIKit. But using those frameworks is more convenient, safe and
efficient than building those abstractions yourself.

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]

The food in the mouth is mixed with saliva,


Salivary which dissolves the starches, converting them into
Digestion sugar. The starches are the only foods whose
chemical digestion is begun in the mouth. They are
first broken up into dextrin and then into the more simple sugar,
known as animal starch, or maltose. Hereafter, in speaking of sugar,
after it has been absorbed into the blood, the reader will bear in mind
that the term refers not only to digested sugar, consumed as such,
but also to digested starches (maltose), as shown on page 63.
It is important that sufficient saliva be mixed with the food, through
mastication, that it may enter the stomach and there continue the
chemical process of digestion of starch. If starches are not
thoroughly masticated, sufficient saliva will not enter the stomach to
convert the starch into sugar; the food will pass into the small
intestine, which must then do more than its normal work of digestion.
The saliva consists of about ninety-nine and one-half per cent
water and one-half per cent solids. The solids consist of ptyalin,
sodium chlorid, sodium carbonate (baking soda), mucus, and
epithelium. Ptyalin, the most important of these, is an active
digestive agent; the mucus lubricates the masticated food; the
sodium carbonate insures the alkalinity of the food; the salt is
present in all secretions; and the water dissolves the food that the
juices may more readily reach and act upon each particle.
The saliva flows into the mouth, more or less, at all times, but
more copiously during mastication. Its evident purpose, when food is
not present, is to keep the lining of the mouth moist.
The flow of saliva is controlled, to a great degree, by nerves which
have their centers in the medulla oblongata. The sight of food,
pleasingly served, or even the thought of food which one likes, will
increase the salivary flow. This is one instance of the control of
thought materially affecting digestion, and the importance of forming
the habit of cultivating a taste for all kinds of food, is apparent. The
stronger the relish for the food, and the more thoroughly it is
masticated, and mixed with the saliva, the more perfect will be the
first step in digestion. This first step of thorough mastication is all
important, not only because the chemical action upon the starch
molecules is facilitated by the thorough softening and mixing with the
saliva, but thorough mastication also tends to prevent overeating.
Water encourages the flow of saliva and for this reason should be
drunk copiously before meals, particularly where digestion is weak. It
may also be taken at rest periods during the meal. (See page 44).

As the food enters the stomach, the gastric juice


Stomach pours out from the mucous lining, very much as
Digestion the saliva pours into the mouth. It consists of
ninety-nine and one-half per cent water and one-
half per cent solids, as does the saliva. The solids of the gastric juice
are composed of pepsin, rennin, hydrochloric acid, and mucus. The
mucus serves to lubricate the food as in the saliva. It also prevents
the digestion of the mucous lining of the stomach itself.
The hydrochloric acid and the pepsin cause the principal chemical
changes in the food while in the stomach, acting alone upon the
proteins. The only digestion of starches in the stomach is that
continued by the saliva. The salivary digestion proceeds until the
gastric juice is secreted in sufficient quantity to cause a marked
acidity of the stomach contents, when the starches are passed into
the intestines.
Gastric juice begins to flow into the stomach soon after eating, but
it is not secreted in sufficient quantity to supersede salivary digestion
for from twenty to forty-five minutes.
The result of gastric digestion of proteins is their conversion, first,
into albumin, then into proteosis and, lastly, into peptone, which is
protein in a more simple, soluble, and diffusible form. In the form of
peptone, the proteins are in condition to be absorbed.
If the food has been properly cooked and masticated the gastric
digestion will be completed in one and one-half to three hours. If not
properly cooked and masticated, the stomach digestion may
continue one to two hours longer. It should, however, be completed
in three hours.
The most readily digested animal foods remain less time in the
stomach. Meat, as a rule, is easily digested, because the action of
the digestive juices of the animal has converted the starches and
sugars. The white meat of chicken, being soft, is digested in a
shorter time than the red or the dark meat.
Fluids leave the stomach more rapidly than solids. Seven ounces
of water leave the stomach in one and one-half hours, seven ounces
of boiled milk in about two hours.
The flow of gastric juice, as the flow of saliva, is governed by the
nerves;—the sight, taste, and smell of food, and the attitude of mind
toward it, to a certain extent, regulates its flow.
After the food has extensively accumulated, during the progress of
a meal, the stomach begins a series of wave-like movements called
peristaltic waves.[4] These waves work downward through the length
of the stomach towards its lower opening, known as the pyloric
orifice. As the food is moved down the stomach by these motions, it
is thoroughly mixed with the gastric juice.
During the early stages of digestion, the sphincter muscles of the
pylorus keep the lower end of the stomach closed, but, as digestion
progresses, the pylorus gradually relaxes to let the digested, soluble
portion of the food pass into the intestine. If the food still remains in a
solid form, by reason of being improperly cooked or poorly
masticated, as it touches the pylorus, these sphincter muscles,
almost as if they were endowed with reasoning faculties, close,
forcing the undigested mass back to be further acted upon by the
gastric juice,—the solid mass is not allowed to pass until dissolved.
If the individual continues to abuse the stomach and to cause it to
work overtime, it becomes exhausted and demands rest; it refuses to
discharge the gastric juice in proper proportion; the peristaltic
movements are weak; and food is not promptly or forcefully moved
along the stomach and mixed with the gastric juice. This demand for
a rest is termed Indigestion.
To sum up,—digested sugar is dextrose; digested starch is first
dextrin, then maltose (animal, sugar); digested protein is peptone;
and, digested fat is saponified fat.

The food passes from the stomach, through the


Intestinal pylorus into the small intestine. The first twelve
Digestion inches of the small intestine is known as the
duodenum. In the duodenum it is acted upon by
the pancreatic juice from the pancreas, the bile from the liver, and
the intestinal juices. These juices act upon proteins, fats, and
carbohydrates. The bile acts upon the fats, while the pancreatic and
intestinal juices act chiefly upon the carbohydrates.
As the food enters the intestine, it is changed, by the sodium
carbonate, from the acid condition produced in the stomach, to
alkaline reaction.
The bile exercises an important influence upon digestion, any
disturbance in the flow of this greenish-brown secretion being very
quickly shown both in stomach and intestinal digestion. It
emulsonizes and saponifies the fats, it aids in their absorption, and it
lubricates the intestinal mass, facilitating its passage through the
entire length of the intestines. Thus, it is a very potent agent in
regulating the bowel movements. A diminution in the flow of bile
quickly expresses itself in constipation.
Fats are almost entirely digested in the small intestine. The
presence of fat stimulates the flow of pancreatic juice, which, in turn,
stimulates the flow of bile from the liver. For this reason, if the liver is
sluggish, fatty foods are desirable. Olive oil is prescribed for gall
stones to stimulate the action of the bile ducts.
Before the fat molecules can be absorbed, they must first be
broken up into glycerin and fatty acids and further changed to a fine
emulsion, which gives the contents of the small intestine a milky
appearance. After they are broken up into these fatty acids and thus
brought to the finest state of emulsion, they are readily saponified,
being then soluble in water and in a state to be absorbed by the
walls of the intestines. The fats are absorbed almost entirely in the
small intestine,—mostly in the duodenum.
As a rule, the starches, or dextrin, will not be fully digested by the
saliva and those which have failed of salivary digestion are acted
upon by amylase (one of the solids of the intestinal juice) and
changed to maltose, while the trypsin from the pancreas, together
with the intestinal juice, acts upon any protein which has failed to be
fully digested in the stomach, changing it into peptone. In the form or
peptone it is absorbed through the “sucking” villi of the intestinal
walls.
The food is forced along the intestinal tract by peristaltic or
muscular relaxation and contraction waves, as in the stomach. As it
is so forced, the nutrient elements, after being put into condition for
absorption, are taken up through the villi of the intestinal walls by the
portal veins and the lacteals of the sub-mucous lining. (See page
78).
It is now believed that a larger proportion of food is digested and
absorbed than was heretofore realized, and that the excretions from
the intestines are, in many cases, made up almost entirely of refuse,
and of the catabolic waste of the system. In an ordinary, mixed diet,
it is stated that about ninety-two per cent of the proteins, ninety-five
per cent of the fats, and ninety-seven per cent of the carbohydrates
are retained by the body.
In digestion, it is of the utmost importance that the
muscular, mucous, and the sub-mucous coats, and the
secreting glands of the stomach and intestines be kept
thoroughly strong and active, that the digestive juices may
be freely poured out, the nutriment be freely absorbed,
and the food be moved along the digestive tract. The
strength of any organ is gained through the nutriment in
the blood; therefore, daily exercise, which calls the blood
freely to these organs, is imperative.
The greater part of the food is absorbed through
Absorption of the intestines, yet some proteins, which have been
Food fully digested by the gastric juice, and certain fats,
particularly the fats in milk, which are in a natural
state of emulsion, may be absorbed through the walls of the
stomach. However, the absorption through the stomach is small
compared to that through the intestines.
The small intestine is particularly fitted for absorption. Every inch
or so along its course the mucous lining is thrown up into folds, as if
to catch the food as it passes toward the large intestine, and to hold
it there until the villi have the opportunity to absorb it. These
transverse folds of the intestinal walls are called valvulæ
conniventes. The villi are fingerlike projections of the mucous lining
of the intestines, which stand out upon the lining somewhat as the
nap on plush. They have been called “sucking” villi, because during
the movements of the intestines they seem to suck in the liquid food.
As soon as the foodstuffs,—proteins, carbohydrates, and fats, are
put in a dissoluble state ready for absorption, they are very promptly
absorbed by the villi. If, for any reason, they remain unabsorbed,
they are liable to ferment by the action of the trypsin, or to be
attacked by the bacteria always present in the intestines.
The peptones, sugars, and saponified fats are rapidly absorbed,
while the undigested portion, together with the unabsorbed water,
the bile, mucus and bacterial products, are passed through the ileo-
cecal valve into the large intestine.
That the large intestine is also adapted to the absorption of fats is
shown by clinical experiments with patients who cannot retain food in
the stomach, the food in such cases being given through rectal
injections.
In the large intestine, the mass passes up the ascending colon,
across the transverse colon, and down the descending colon, losing,
by absorption, foodstuffs not absorbed in the stomach and small
intestine.
While water and salt are absorbed both in the stomach and in the
small intestine, the evident purpose in leaving the larger part of the
water to be absorbed in the large intestine is that it may assist the
intestinal contents in passing along. The water also stimulates the
peristaltic movement.
As the food is absorbed through the walls of the alimentary canal,
it is picked up by the rootlets of the mesenteric veins[5] and by the
lymph channels,—the latter, through the abdominal cavity, are called
lacteals. Nearly all of the fats are absorbed through the lacteals. The
whitish color given to the contents of the lacteals, by the saponified
fats, gives rise to the term lacteal, meaning “whitish.”
Nearly all of the proteins and sugars pass through the mesenteric
veins and the portal veins into the liver. Here the sugars are at once
attacked by the liver cells and built up into glycogen as described on
page 81 and the proteins are passed through the liver into the
arterial blood stream. A small portion of the proteins, however, do not
go to the liver, but are passed directly into the lymphatics and thus
into the blood stream, where they are again carried to the liver.
To sum up,—the larger part of the absorption of sugars, starches,
proteins, and fats is through the small intestine, though some are
absorbed in the stomach and a very little through the large intestine;
while some water and salts are absorbed in the stomach and small
intestine, these are largely absorbed in the large intestine.
FOOTNOTES:
[3] A knowledge of the mucous lining of the stomach and
intestines, and of the tributary glands, such as the liver and
pancreas, is important to a thorough understanding of digestion,
and the reader is referred to “The Vital Organs: Their Use and
Abuse” of this series. This takes up the study of the secretion of
digestive juices, the conditions favoring normal secretions, etc.
[4] See “The Vital Organs; Their Use and Abuse” by Susanna
Cocroft.
[5] For illustration see the frontispiece of “The Circulation,
Lungs, Heart,” of this series.
The Work of Various Organs Affecting
Digestion
The purpose of this chapter is to show the work of other organs
than the digestive organs in converting the digested food to use in
the body, in tearing down waste, and in eliminating waste and an
excess of material above the body needs.

The liver is commonly called the chemical work-


Work of the shop of the body. The proteins and sugars are
Liver carried through the blood (portal veins) to the liver
directly they are absorbed from the alimentary
canal. As the food materials filter through the blood capillaries,
between the liver cells, several substances are absorbed, particularly
sugar, which is here changed into animal starch called glycogen. It is
held in the liver for a few hours in the form of glycogen and then
redigested by the action of an amylolitic ferment and again gradually
given out into the blood in the form of sugar; hence sugar is subject
first to the anabolic change of being built up into glycogen, and then
to the catabolic change of oxidation and breaking down.
While the conversion of the sugar is one chief office of the liver, it
also acts upon the proteins,—not as they are first passed through
the liver in the blood, but as they are returned to the liver from the
muscle tissue, partly oxidized and broken up into simpler products.
The liver cells absorb and further oxidize and combine them into
nitrogenous waste, which the kidneys throw off in urea.
The liver and the spleen also break up the pigment or coloring
matter of the red blood corpuscles. As they become worn out, they
are retired in the liver and the spleen from the circulation. The iron is
retained by the liver cells and the remainder is thrown off from the
liver, in the bile.
The liver is often called the watch dog of the body, because it is on
guard for all poisons which pass through it in the blood. The large
part of these toxic substances are absorbed through the alimentary
canal with other foodstuffs. Many of them are the result of the
fermentation of foods which are not digested as promptly as they
should be, on account of an insufficient secretion of digestive juices,
or a failure to secrete them in normal proportions, or due to inactivity
of the stomach and intestines.
It surely is a wise provision of nature to supply a guard to oxidize,
or break down these poisons and make them harmless, so that they
do not pass to all parts of the body as poisons, thus affecting the
nerves and the blood stream, and, through these, the entire system.
The necessity of correct habits of deep breathing will be readily
seen, because oxygen is required to break down the poisons as well
as to oxidize the waste of the system.
One example of the action of the liver in rendering substances
harmless, is its oxidation of alcohol. From one to three ounces of
alcohol a day are oxidized and made harmless in the liver, varying
according to the individual and to the condition, at different times, in
the same person. If the limit of one to three ounces is exceeded, the
excess is not oxidized and intoxication results. These evidences of
intoxication are in the nature of narcosis; alcohol is now regarded as
a narcotic along with ether and chloroform.
It was formerly held by physiologists that alcohol was a food,
because its oxidation liberates body heat and it was assumed that
this liberation of heat, was the same as that freed by the combustion
of fats, starches, and sugar uniting with oxygen. More recent
knowledge, however, has unquestionably determined that heat,
resulting from oxidation of alcohol, does not keep up body
temperature; the pores of the skin are opened and there is a greater
loss of heat through the skin. This really makes the system less able
to resist cold. Large doses of alcohol actually cause a fall in body
temperature and every force of the body is decreased in efficiency,
while if alcohol were an actual food the efficiency would be
increased. We are forced to the conclusion, therefore, that alcohol is
a pseudo-food as it is a pseudo-stimulant.

The muscles play an important part in the use of


Work of the foods. Most of the heat is generated in them, by
Muscles the sugar and fats coming in contact with the
oxygen in the blood. This heat is liberated during
every moment of the twenty-four hours, asleep or awake. Of course,
more is liberated during exercise, since the movement of the
muscles sets all tissues into activity and the blood circulates more
strongly, bringing a greater supply of oxygen to them. It is always
well during active exercise to stop frequently and fully inflate the
lungs. The effort should always be made to breathe fully and deeply
—otherwise the pressure of the liberated carbon dioxid will cause a
pressure throughout the blood stream, particularly about the heart
and in the head. This pressure is relieved when the excess of
carbonic acid gas liberated has been thrown off by the lungs. Nature
makes the effort to throw off the excess of carbonic acid gas by
forcing one to breathe more rapidly while running or taking unusual
exercise.
The oxidation changes are simply a combustion of sugars and
fats, liberating latent heat as they are brought into contact with the
oxygen. Exercise and a regulation of the amount of carbohydrates
and fats consumed in the foods is the natural, scientific method for
the reduction of an excess of fat.
A certain amount of protein is constantly oxidized in the muscles,
also, being broken down into carbon dioxid, water and a number of
nitrogenous mid-products. The carbonic acid gas and water are
thrown off by the lungs and the partially oxidized, nitrogenous waste
is carried to the liver, where it is further oxidized and prepared for
excretion, through the kidneys, lungs, skin and intestines.
When sugar is carried to the muscles in larger quantities than can
be utilized by them, it is often built up into animal starch and stored
in the form of glycogen, similar to its chemical change and storage in
the liver.
This storage of glycogen in the muscles and in the liver is a wise
provision of Nature. It is a reserve to be called upon whenever the
expenditure of heat and energy exceeds the amount supplied in any
day’s rations.

The nerves oxidize food materials, but not to any


Work of the great extent, excepting during nervous activity.
Nerves During periods of rest, food materials are stored in
the nerve cells in grandular form. They represent
concentrated nerve foods and are the result of anabolic processes.
During nervous activity they are oxidized and carried away through
the blood and the lymph. This oxidation of the food, stored in the
nerves, creates nervous energy and heat.
The energy liberated by the nerves resembles electrical energy.
Where one subjects himself continuously to an excess of nervous
activity, all reserve food material, stored in the nerve cells, is used
and the result is a trying nerve tension. Such individuals need plenty
of easily digested food.

The lungs absorb oxygen and eliminate carbon


Work of the dioxid. They occasionally throw off a very little
Lungs organic material.
The carbon dioxid is carried to the lungs from the tissues through
the venous stream and diffused through the capillary walls of the
lungs. The oxygen is absorbed into the capillaries through the thin air
sacs in the walls of the lungs.
The kidneys do not absorb as do the lungs,
Work of the neither do they perform any anabolic work as does
Kidneys the liver, nor catabolic work as the muscles, nerves
and the liver. They simply throw off waste matter.
The blood passes through them in a transverse branch from the
abdominal aorta. In its circuit urea, uric acid, urates, sulphuric acid,
sulphates and sodium phosphates pass from the blood with the
water and are thrown from the system; hence the kidneys are
purifying organs, as are the lungs. The blood returning from the
kidneys through the veins is pure, just as the blood in the pulmonary
vein is pure, while that in the arteries to the kidneys and the lungs is
impure.
The above substances cannot be thrown off from the lungs. They
are the products of oxidation of proteins, partly of the living tissues
and partly those broken down direct as they are supplied in the
foods, in excess of the needs of the system.
Interference in the action of the kidneys results in a hoarding of
these substances in the blood, and may produce an intoxicated
condition known as uremic poisoning.
Water in abundance and diuretic fruits and vegetables, which
increase the activity of the kidneys, should be taken where uremia is
indicated. (Foods which cause a free flow of urine are called diuretic
foods.)
The sweat glands also throw off an excess of
Work of the Skin water and salts. The kidneys and the skin are
interdependent; if the kidneys are inactive the skin
throws off a larger quantity and if the skin is inactive, or if for any
reason the pores of the skin are closed, the kidneys are more active.
This is evidenced by the sudden immersion of the body in cold
water; the pores of the skin being closed the kidneys immediately
act.
During the summer, or at any time when the skin throws off more
water than usual, the kidneys are less active and the urine, being
more concentrated, is darker.
The skin also throws off carbon dioxid and, to a slight extent, it
absorbs oxygen.

The intestines, in their work of elimination, pass


Work of the off all undigested matter. They also carry off bile
Intestines pigment, bile salts, mucus, amino acids, and other
decomposition of proteins,—also a little
unabsorbed fats and bacterial decomposition taking place in the
intestines. Coarse articles of food containing fibres which do not
digest, such as the bran of grains and the coarser fruits and
vegetables (though much of their substances are not food in the
strictest sense) are valuable to increase the peristaltic movements of
the intestines and to act as a carrying body to move the waste
excretions along their course.
The combustion, or burning of fuel in any form, (oxidation for the
release of latent heat and energy) always leaves some parts which
are not used as heat or energy, and it is the work of the intestines to
eliminate much of this refuse. When coal is burned, gas, smoke and
cinders or clinkers, constitute the waste and if these were not
allowed to escape from a stove the fire would soon go out—the
smoke and gas would smother it and the clinkers would prevent the
circulation of oxygen and soon clog and fill the stove. The same is
true in the body—the carbonic acid gas not being allowed to pass off
would soon put out the fires of life; it would poison the body and
stunt the action of the nerves. If the nitrogenous waste (like ashes
and cinders) is not eliminated by the kidneys, one will die in
convulsions in one or two days.
The absolute necessity of a free elimination of waste will be readily
seen.—If the engine is to do its best work, the engineer sees that it is
kept perfectly clean—otherwise it becomes clogged, does inefficient
work and the clogging soon wears out some parts. The same is true
in the body,—clogging in any part overworks and wears out other
parts dependent upon the work of the one.
Summary
Let us sum up the processes which the food undergoes in its
conversion into condition to be absorbed by the body; in its
absorption through the walls of the intestines and stomach; and the
metabolic processes which it undergoes in being converted into heat
and energy and again broken down and eliminated as waste.
The Saliva begins the digestion of starches and sugars in the
mouth. This digestion is continued by the saliva in the stomach.
The Stomach, when in normal condition, thoroughly digests the
proteins. If any proteins fail of digestion in the stomach the process
is completed in the intestines.
The Intestines, aside from their work of digestion and absorption,
excrete bile pigment, bile salts, animal acids, mucus and other
decomposition of proteins, with bacterial fermentation and
putrefactions; also such food materials as are not digested.
The small intestine digests and absorbs the fats and continues the
digestion of starches, sugars and fats when this digestion is not
completed in the stomach.
The large part of the food is absorbed through the small intestine,
though a small part is absorbed through the walls of the stomach
and through the large intestine.
Fats are almost entirely absorbed in the small intestine. They are
absorbed through the lacteals and are carried into the blood stream.
The Liver. The proteins and the starches (converted into maltose)
and sugars pass into the liver. The sugar (including the sugar in
vegetables, milk, fruits and that used for sweetening, as well as the
carbohydrates which have been changed into maltose), is converted
into glycogen in the liver, stored here for a time and again broken
down into sugar that it may be in condition to be absorbed into the
blood.
The proteins pass through the liver but are not acted upon by this
organ until they again return to the liver through the blood stream,
after they have been partly oxidized in the tissues. The liver further
oxidizes them putting them into condition to be excreted by the
kidneys and intestines.
The liver also breaks up the worn out red corpuscles, putting them
into condition to be eliminated in the bile.
It oxidizes and renders harmless poisonous substances absorbed
in the food, such as fermented food products and alcohol.
The Muscles oxidize the fats and sugars liberating the latent heat
and energy.
They partly oxidize proteins which are further broken up in the
liver.
The Nerves oxidize food materials stored in the nerve cells,
providing nervous energy.
The Lungs absorb oxygen and throw off carbon dioxid, watery
vapor and some organic substances.
The Kidneys and The Skin purify the blood by excreting water,
carbon dioxid and nitrogenous waste.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like