100% found this document useful (5 votes)
40 views

Instant Ebooks Textbook Combine Asynchronous Programming With Swift First Edition Scott Gardner Download All Chapters

Programming

Uploaded by

bintenjwbi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
40 views

Instant Ebooks Textbook Combine Asynchronous Programming With Swift First Edition Scott Gardner Download All Chapters

Programming

Uploaded by

bintenjwbi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Download the full version of the textbook now 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/

Explore and download more textbook 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/

textbookfull.com

RxSwift Reactive Programming with Swift 1st Edition


Florent Pillet

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

textbookfull.com

Asynchronous Android Programming Helder Vasconcelos

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

textbookfull.com

Construction Contracts Questions and Answers 4th Edition


David Chappell

https://textbookfull.com/product/construction-contracts-questions-and-
answers-4th-edition-david-chappell/

textbookfull.com
Enabling People with Dementia Understanding and
Implementing Person Centred Care Pat Hobson

https://textbookfull.com/product/enabling-people-with-dementia-
understanding-and-implementing-person-centred-care-pat-hobson/

textbookfull.com

Developments in Object Relations Controversies Conflicts


and Common Ground 1st Edition Lavinia Gomez

https://textbookfull.com/product/developments-in-object-relations-
controversies-conflicts-and-common-ground-1st-edition-lavinia-gomez/

textbookfull.com

Microbial Environmental Genomics MEG 1st Edition Francis


Martin

https://textbookfull.com/product/microbial-environmental-genomics-
meg-1st-edition-francis-martin-2/

textbookfull.com

R For College Mathematics and Statistics 1st Edition


Thomas Pfaff

https://textbookfull.com/product/r-for-college-mathematics-and-
statistics-1st-edition-thomas-pfaff/

textbookfull.com

The Power of Anticipatory Images in Student Achievement


1st Edition James M. Davy

https://textbookfull.com/product/the-power-of-anticipatory-images-in-
student-achievement-1st-edition-james-m-davy/

textbookfull.com
Security and Cryptography for Networks 10th International
Conference SCN 2016 Amalfi Italy August 31 September 2
2016 Proceedings 1st Edition Vassilis Zikas
https://textbookfull.com/product/security-and-cryptography-for-
networks-10th-international-conference-scn-2016-amalfi-italy-
august-31-september-2-2016-proceedings-1st-edition-vassilis-zikas/
textbookfull.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
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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
Random documents with unrelated
content Scribd suggests to you:
your lord, and you have not acted as if you were my men and did
this out of loyalty to me. Now it will be necessary for you to suffer a
swift revenge and a prompt punishment, lest this deed draw you into
everlasting torment.” Then David ordered his men to cut off their
hands and feet and afterwards to hang them beside a pool in a city
called Hebron.[317]
LXIII

THE JUDGMENTS OF GOD ILLUSTRATED BY THE STORY OF DAVID AND SAUL

Son. I will venture to ask one more question about those cases in
which it seems to me that God has passed rather strange sentences.
I am asking chiefly because I find it hard to understand what reason
or circumstance can have caused the difference in these decrees
which I now intend to bring up. You stated earlier in your speech
that God deprived Saul of his kingdom because he was too lenient in
cases of homicide, though a man will think that this was no great
offence, as it is easy enough to slay multitudes if that be regarded a
better deed than to let them live. Still, this leniency proved such a
grievous fault that God said He regretted having chosen Saul king
over his people, and immediately threatened—what He later carried
out—that the kingship should never be transmitted to his
descendants; and immediately, though Saul was still living, He
appointed another to be king after his days. But after David had
become king, he committed a crime which will scarcely seem less
when reflected upon; for he committed adultery with the wife of
Uriah his knight, a good and faithful man, and afterwards contrived
his death, not as a just penalty but because he wanted his wife. But
later, when Nathan the prophet pointed out the sin to David and he
confessed, he was forgiven at once; indeed, it seemed as if his
kingship was more stable after that time than before. Now I do not
know which is the worse crime, to kill an innocent man and violate
his wife, or to let the guilty have their lives. Many a man, who is
ignorant as to the reason why, may indeed imagine that God loved
David more than Saul, and that David’s crime was counted less for
that reason. But inasmuch as God always judges according to justice
and without regard to persons, it would be sinful to hold wrong
ideas about this; and it would be well if you could add a few words
in explanation, unless you think that my questions are stupid. It may
also be that great lords who are chosen to be judges will get a
better insight into these things, if they are clearly expressed.
Father. This question is of such a character that it will demand an
extended answer, if it is to be fully understood. But since it has been
brought up, I shall be glad to answer it as far as I can and as briefly
as I can. First it is necessary to recall what I said in an earlier
speech when we talked about dooms,—when they should be severe
and when lenient: I then brought out the fact that if a good and
peace-loving man should fall into sin and his deed should seem evil
to him and he were anxious to do penance, then the judgment
ought to be merciful in his case on account of human nature; for
human nature is so frail that no one can be so careful as never to
fall into sin. But some add to their offence by taking pride in it, and
they are not careful to avoid falling into another sin. Now David was
of all men the most adroit in the use of weapons in warfare and he
was by nature quite severe in righteous chastisement; but he was a
kind-hearted man, friendly toward everyone, and sympathetic
toward all who suffered misfortunes. He was also trustworthy in
every respect, honest and faithful in friendship and in all his
promises, and so virtuous that he would allow nothing vicious about
his person,—indeed his like was not found among all the people of
Israel; for when God chose David to be king, He testified in these
words, saying that He had found a man after His own heart. But
human frailty caused him to fall in the matter that we mentioned
earlier: he violated Uriah’s wife. But after he had fallen into this
transgression and when he was once more alone, he repented
deeply, sighing and weeping. Inasmuch as the rules of the law would
condemn this crime as a shameful reproach, if it were rumored
among the people, David planned to keep the matter quiet, letting
God see his repentance but keeping the people in ignorance of his
offence, lest they should take his misdeed as an example and regard
it as less serious to fall into sin and transgression if they knew of his
guilt. So David sought to hide his guilt by a crafty design: for as
soon as he learned that Bathsheba, Uriah’s wife, was pregnant, he
sent for Uriah, and hoping to avoid taking his life, he ordered him to
lie with his wife so that the offspring might be known as his, while
David would atone in secret for the sin of his whoredom and never
afterward come near Uriah’s wife. But when he found that Uriah
happened to be unwilling to lie with his wife, he contrived to conceal
his sin from men, though he increased it in the sight of God. Later,
when Nathan the prophet charged David with all this guilt, he
answered as if condemning himself, speaking these words: “So
heavy and evil is my transgression that I am worthy of death
because of this thing; a wretch am I to have set such an example
before God’s people, over whom He has appointed me ruler and
judge; rather would I now suffer a speedy death than have this
misdeed pursue me to hell. Now since I have set an evil example
before the people of God by my sin, I am ready to suffer punishment
according to the Lord’s will as a warning to the people not to fall into
such transgression.” But when Truth and Justice saw David’s
penitence, they permitted Mercy to pass the judgment; for the
prophet Nathan replied in this wise: “God sees your repentance, and
He does not desire you to suffer death for your sin, but He will
punish you with an endurable chastisement for this deed before you
die.” Now you must know that God did not forgive David’s crime so
completely as to excuse him from just punishment; for this was the
first penalty that the king suffered from God: the child which he had
begotten with Bathsheba was a man child and very lovely, wherefore
David much desired that it might live; but it did not please God to let
him enjoy the child which he had begotten in such a sinful way.
Nevertheless, David lay seven days upon the earth in the raiment of
mourning, fasting and imploring God to let the child live. But God
would not hear his prayer, and the child expired on the seventh day.
[318]
And this was the second punishment, that God refused to let
David build him a temple;[319] God even called him a murderer,
because he had deprived Uriah of life. But for the adultery which he
had committed with Uriah’s wife, he had to suffer this disgrace, that
his son Absalom, in the sight of all the people, went in unto David’s
concubines and thus dishonored his father before all the people.[320]
You have also asked which crime was the worse, that David
caused Uriah to be slain without guilt and seduced his wife, or that
Saul refused to kill so many people of Amalek; and you shall know of
a truth that Saul’s crime was the greater; for no offence is graver
than to be disobedient toward one’s superiors, as Saul was. And you
may observe even at this day among cloister folk, that if a monk is
disobedient toward his abbot, where an abbot rules the cloister, or
toward the prior, where such a one controls, he is forthwith expelled
from the holy order and from the monastery and is thenceforth
regarded as a layman. Likewise, if a priest refuses to obey his
superior the bishop, he is at once deprived of clerical honors, and
the right to say mass is taken from him as well as all other official
duties. In the same way, if a bishop, be he humble or powerful,
refuses to obey his superior, he is immediately shorn of his dignity
and all his office; and after that he is regarded among learned men
as any other layman unworthy of any distinction. And it ought to be
even more evident that it could not prosper Saul to be disobedient to
such a lord as God Himself, when he was ordered to invade Amalek
and the land of the Amorites and to slay all that was living. God took
His rod of punishment and placed it in Saul’s hands, bidding him
execute His wrath and spare nothing that was living; to burn fortified
cities, farmsteads, clothing, and whatever else there was; to lay the
entire land in ruins and thus cleanse it with sword and ax and fire.
Saul, however, carried out the vengeance that he was charged with
in another way, by destroying everything that was lacking in beauty
or value; but whatever seemed to him to be beautiful, valuable, and
worth possessing he spared, brought home to his country, and
distributed among his men. But when Samuel came to Saul and
showed him the wrath of God, Saul spoke as if excusing himself:
“Praise be to God, for I have fulfilled His command: I invaded
Amalek and visited the entire kingdom with fire and sword; but King
Agag I have brought with me, wishing to honor God’s command by
slaying him here, if He wills that he die. Fat oxen and fine sheep I
have brought hither to sacrifice such to God as are acceptable to
Him; and the children of the chief men I have brought hither to be
kept in bondage and distress, doing fitting service for ourselves.”
Then Samuel replied: “How can God now accept that as a sacrifice
which He has Himself cursed in His anger? For God demands a
blessed and not an accursed sacrifice; and you shall know of a
surety that obedience is more pleasing to God than any sacrifice.”
Truth stood by and said: “What need is there to conceal the motive
that induced Saul to neglect doing as God commanded him? Saul
imagined himself so firmly established in his kingship that he could
order these things more according to his own liking than to God’s
command; he showed excessive pride in failing to remember who
had given him the power. And this is the reason why he took good
horses, oxen, sheep, and much else of value, that he might satisfy
the greed of his knights and the rapacity of his other warriors rather
than carry out the commands of God. And he spoke falsely when he
said that he had brought horses and sheep and other things of value
into his kingdom to sacrifice them to God; for he knew that a cursed
sacrifice was not acceptable to God.” Then the decision was left to
Justice and she decreed in this wise: “Whereas God took His rod of
punishment, and placing it in Saul’s hands bade him execute the
divine wrath upon a cursed people, let that punishment now come
upon Saul and his family which he failed to visit upon those whom
God had commanded him to carry it out upon. But the same rod of
punishment that was given to Saul to shake over others, another
shall now hold and shake over Saul and all his kin. And because he
wished in his avarice to possess the riches that were forbidden him,
let him now forfeit those riches that were given to him before.”[321]
But the reason why Justice passed such a severe judgment upon
Saul was that God knew his disposition thoroughly. For it was in
Saul’s nature to be proud and stubborn in the face of God; and as
soon as he thought himself firmly established in his kingdom, he
became greedy and avaricious, as is evident from this account.
Now there was this difference between the tempers of David and
Saul: when Nathan the prophet charged David with sin, he spoke
reproachfully of his fault, almost as if condemning himself, and
implored mercy, though willing to suffer punishment, as if prepared
to accept with gratitude any terms which God might impose for his
misdeed; therefore he won favor through the lenient judgment of
Mercy. Yet, his son died because of Uriah’s death, though David
himself did not die; and for violating Uriah’s wife he suffered a great
disgrace in that his son dishonored him in the sight of all the people.
But when Samuel accused Saul of his crime, he replied as if
defending his cause and praised himself for having done so well and
spoke in this wise: “Praise be to God, for I have done what He
commanded;” though he knew in his own mind that anything else
was nearer the truth. Therefore he was stricken by the sentence of
Justice, God seeing his arrogant boasting and lying excuses. But his
arrogance and envy became even more evident after he discovered
that God was angry with him; for Saul fell ill; and now and then
madness came upon him, so that he had to be watched when the
malady troubled him. Then it was learned that if a man could be
found who could play the harp well before him, he would find relief
and the illness would afflict him less. So they found a lovely youth
whose name was David, the son of Jesse in Bethlehem, who knew
how to strike the harp skilfully; he came to the king, and whenever
the malady came upon Saul, David, standing before him, struck the
harp and the illness departed immediately. But when Saul discovered
that the malady was less severe, he loved David highly and made
him his shield bearer.[322] Samuel, however, had already anointed him
king in secret, no one knowing it but his father and his brothers.
David remained with Saul many days and served him faithfully; and
all men perceived that God was with him in all his doings. Saul, too,
was well disposed toward him at first: he gave him his daughter and
assigned him a troop to command.[323] But after Saul had won his
great victory over the Philistines and David had slain the giant
Goliath and they were returning from the warfare, women came
forth from cities and fortresses, dancing toward them and singing
praises to them for their victory. And the burden of their song was
this, that Saul had conquered a thousand but David ten thousand.
[324]
When Saul heard this he was seized with wrath and envy toward
David and said in his own thoughts: “Now I perceive that God has
chosen this man to take the kingdom after me instead of my sons;
but I shall try to upset this plan if I can, though so cleverly that no
one shall perceive that I kill him intentionally.” A few days later Saul’s
habitual illness came upon him; but David took his harp and,
standing before him, played as was his wont to relieve the king’s
illness. Saul had a javelin in his hand which he threw at David,
aiming to drive it through him and pin him to the wall of the room.
Thus he had planned to avoid responsibility for the murder by
leading the people to think he had done it in frenzy and not with evil
intent. David escaped and found security from that peril. But when
Saul saw that David had escaped and he had not caught him, he
sent him on frequent forays among heathen people in the hope that
he would be slain in warfare. But the more frequently David went
out into battle, the more frequent victories and the greater honors
did he win; and God magnified him before the eyes of all the people.
And the more Saul saw him prosper, the more he envied him.[325]
Now you can imagine the state of King Saul’s mind: he could say
nothing against David, only what was good. But since he perceived
that God loved David much because of his humility and loyalty, he
envied him as Cain envied his brother Abel because God loved him.
Indeed, Saul’s enmity toward David became so evident that he could
not conceal his intentions to kill him. Then Jonathan, Saul’s son,
reminded the king that it would be a sin to slay an innocent man,
speaking in this wise: “My lord, why are you angry with your servant
David? If there is any guilt on his part that may be injurious to your
kingdom or dignity, every man who is with you here will seek his life;
and we can seize him whenever we like, for he is not on his guard
against us, knowing himself to be guiltless. He has served you long
and has been faithful in all things; he fought against great odds
when he slew Goliath, and God rescued your entire kingdom through
David’s wonderful victory, which he won fighting unarmed against a
giant. He has waited upon you in your distressing illness; and
wherever you have placed him at the head of the host, he has
brought a vigorous defense to your kingdom, and no one knows that
he has been anything but loyal. Therefore conquer your wrath, sire,
and do not fall into such an evident sin of murder before God as to
slay an innocent man.”[326] Saul, however, became only the more
wrathful and charged with treason his son and everyone else who
spoke a good word for David.
David fled from King Saul’s wrath with a few men, but provided
with neither clothes nor weapons. He came to the city called Nob,
the bishop of which was Ahimelech, a son of Ahitub the bishop; but
Ahitub was the son of Ichabod, the son of Phineas, the son of Eli the
bishop. When David came to the bishop Ahimelech, he pretended to
be traveling on an important mission for King Saul, and asked him to
give him and his men something to eat and to furnish him with
weapons. The bishop Ahimelech gave him such victuals as he had,
but weapons he had none to give him except the sword that had
belonged to Goliath; and this he gave him, for he did not know that
he was a fugitive, but believed he was traveling on the king’s errand,
as he had said. But so fierce was Saul’s hatred toward David, that as
soon as he learned that the bishop Ahimelech had given him food,
he seized the bishop and all his kinsmen and charged them with
treason. The bishop replied to the charge in this wise: “My lord, I
confess that I gave David what food I had and the weapon that I
had, for he said he was traveling on an important errand on your
behalf. Why should I not give hospitality to a man like David, who is
the best and the most highly esteemed of all the men that you have
about you except your sons, and who is furthermore your own son-
in-law and has been faithful to you in all things? Never have I had
any design against you or your honor. Do not think, my lord, that I,
your servant, have plotted with David against your will; I could not
know why David traveled in such distress, for he told me that you
had sent him with important errands; nor did I know that he had
fallen into any guilt against you.” Then Saul replied in fierce anger:
“This I swear that you shall perish to-day, you and all your kin.”
Thereupon he caused the bishop to be slain along with eighty-five
other men, all of whom were robed in the priestly dignity. After that
he ordered all who dwelt in the city of Nob to be slain, even women
and children, and had the city burned.[327]
Now I have revealed to you the ferocity which God found in Saul’s
heart when he removed him from the kingship, and which later
became evident in what you have now heard and in much else of
like import, though I have told this only. The displeasure which the
king incurred from God fell so heavily upon him, for the reason that
God saw in his heart the fierce avarice which later began to appear.
Now he wanted to kill David, though innocent, because he found
that God loved him; and he slew the bishop, though guiltless, and so
fierce was he that he slew everything in the city that had life and
afterward burned the city. But where God had commanded him to
use severity of this sort, there he had spared; here, however, he
slew God’s servants in defiance of God’s command. But in David’s
case God passed a more lenient judgment for the reason that, just
as he perceived the ferocity in Saul’s heart, he found true
repentance and clemency in David’s heart, as I shall now show you.
There was a son of the bishop Ahimelech, Abiathar by name, who
was hid in a cave when all those were slain of whom I have just
spoken. Abiathar fled to David and told him all these happenings.
But when David heard these tidings, he sighed and spoke thus in
deep sorrow: “May God in His mercy forgive me for this slaughter,
for I have too great a share in it, having eaten your father’s bread.
And now since you have come hither, abide with me; and if God
permits me to live, He will also protect you with me, and let
whatever God wishes happen to us both.” Thereupon David elevated
him to the bishop’s office which his father had held. But when
David’s kinsmen learned that he was abiding in the forest, they
joined him with a large force counting not fewer than four hundred
men; and from that time on David grew in strength as God willed.
[328]
He camped among the hills with this force and made repeated
attacks on Saul’s enemies, but never on the king himself or his men.
But whenever Saul learned where David lay concealed, he marched
out to seek him, intending to slay him.
Then it happened once, when David and his men were hiding in a
large cave, that Saul entered this alone on a necessary errand. Then
said David’s companions: “Now God has fulfilled what He has
promised you and has delivered your enemy into your hands; be
sure to secure this quarry.” David stole up and cut a piece off Saul’s
mantle, though the king was not aware of it, and returned to his
comrades. Then David’s companions said to him: “If you are
unwilling to lay your own hand upon him, let us kill him.” David
replied: “My crime would be as great before God, whether I do it
myself or bid others do it. God keep me and all our companions from
such a sin as to lay hands upon the Lord’s anointed. He is my master
and I served him long; he is also the Lord’s anointed and it would be
a great crime, if I were to lay hands upon him, for I have no revenge
to take either for father or brother or any other kinsman; nor is it as
if he had taken the throne which he sits upon from my kinsmen with
violence or deceit; but God chose him to it and sanctified him to His
service, honoring him with His own name. Wherefore it is right that
He Who appointed him to the kingship should deprive him of it
according to His will, but not I in vengeful audacity. And I swear this
day that God alone shall call him, whether by demanding his soul or
by causing him to fall in battle before his enemies; but as for my
hands, they shall let him live many days. But I regret deeply that I
injured his garment if he shall feel hurt or dishonored because of it.”
When Saul had departed and returned to his host, David ran up
on a hill and cried: “My lord, King Saul! can you hear?” But when
Saul turned to hear what this man said, David bent both knees to
the earth and bowing before the king said to him: “Those men do ill
who tell you, my lord, that I mean to be your enemy; for now I have
evidence here in my hand that your life was in my power to-day,
when you left all your host and entered the cave alone; and it was
no less in my power to injure your life than your clothes, for here I
have in my hand a large piece of the skirt of your mantle. Now let
God judge between us. You see how they have told lying tales, who
say that I have striven after your life.” Saul appreciated these facts
fully, for David spoke the truth; and he promised that he would
nevermore hate David.[329] But not many days passed before Saul
went out again to seek David, as he did constantly after that. Now it
came to pass another time, when Saul had made a wearisome
journey in search of David, that sleep came upon the king and all his
host. And David went into the camp where Saul lay, but none was
aware of it. The man who accompanied him was named Abishai and
he said to David: “Now you can see that God surely intends to
deliver your enemy into your hands, and it is not advisable to refuse
what God Himself offers you. I will thrust my spear through him, if
you will permit me, and then we shall return to our men.” David
answered: “God has done this to tempt me and to see whether I
would lay my hands on His anointed. Now I must answer as before,
that God shall tear the kingship from him, either by demanding his
soul or by causing him to fall before his enemies; but as for my
hands, they shall let him live many days; for I have no revenge to
cherish against him, either for plunder or for the loss of kinsmen,
except such as was incurred while he was cleansing the land with
righteous punishment; and it is neither my proper business nor that
of anyone else to take revenge for such; for it is a more serious
matter than even a wise man can conceive to lay hands on the
Lord’s anointed, who is dedicated and hallowed to God. Let us take
his saddle-cup and his spear for a proof, and then let us return to
our forces.”[330]
Now you will understand the character of both King Saul and
David from what I have just told you. David knew that he was
chosen of God to govern, that he was the Lord’s anointed,
consecrated and hallowed to God no less than Saul was. He also
knew that God had rejected Saul. And God delivered Saul into
David’s hands, so that he could have taken Saul’s life at any time, if
he had wished. David showed great faithfulness and humility in this,
that every time he saw Saul, he bowed before him and saluted him
as any other unhallowed layman would, who had not been set apart
for chieftainship. Although Saul lay in wait for his life, David
continued to serve him, and worried the king’s enemies as much as
he could. On the other hand, Saul had nothing against David except
that he knew God had chosen him to be king; and he showed great
wickedness and fierce hatred in striving to slay an innocent man,
one who served him faithfully. He likewise displayed an inordinate
vanity in wishing to make away with a man whom God Himself had
chosen to rule after him. For these reasons God passed a severe
judgment in Saul’s case; for He saw in Saul’s heart what men could
not perceive, though subsequently God made this fact evident to the
sight of men. But in David’s case God was more lenient, for the
reason that He found him always humble and faithful in everything,
as He made clear to men later on. There is further evidence of this
in the fact, that as soon as David learned that Saul and his son
Jonathan had fallen, he and all his host lamented in great sorrow,
and David spoke these words: “Be ye cursed, ye mountains of
Gilboa! May God nevermore send rain or dew or growing grass upon
you, for you led King Saul and his son Jonathan along treacherous
paths in their flight across your summits and refused to show them
serviceable highways, whereby they could save their lives from the
hands of the foeman; nor did you provide them with sheltering
ramparts upon your heights. It is a bitter sorrow for all the people of
Israel, that splendid chieftains like Saul and Jonathan should pass
away from council and government. Great strength and power have
perished this day, when such excellent princes are fallen as Saul and
Jonathan were, and the many good knights with many good
weapons and much good armor who have perished with them. Let
the lesser men beware of God’s wrath, since He has allowed the
heathen to lay hands on His anointed. Let the multitude bewail a
loss like this, that such excellent rulers should fall before the
heathen.”[331] Such words and many more like them David spoke that
day, and thus he lamented their death rather than rejoiced in the
fact that the realm had fallen to him and into his keeping. From this
you will observe how upright he was, how honest and free from
faults. But whenever human nature caused him to fall into sin, he
forthwith showed keen repentance, imploring God’s mercy and
compassion; and God gave heed at once to his honest regret.
Earlier in our conversation we have told how Absalom, King
David’s son, raised the whole land in revolt against his father. But
when David’s captains happened to meet Absalom in battle and
David learned of his death, he cried out in these words: “What shall
it profit me to live, an aged man who grows weaker day by day, now
that you, my son Absalom, are dead in the flowertime of youth?
Would to God that I could die now and that you my son might
live!”[332] David was never so bitter against other men but that he
would rather suffer death himself than see another’s death, except
where he saw that punishment was inflicted on the demand of
justice. This was shown again at one time when David’s entire
kingdom incurred the wrath of God, and a pestilence came upon the
realm, so violent that people perished by thousands. When the
plague approached the city of Jerusalem, David beheld the angel,
who was smiting the people, standing between heaven and earth
with a blazing sword. And when he saw the angel with the sword
lifted as if ready to strike, he placed his neck under the edge and
said: “I beg thee, O Lord, that this sword be rather turned against
my neck than that more of God’s people shall now be slain, and that
my Lord’s wrath may fall upon me, who am guilty and worthy of
punishment, and upon my family rather than that God’s people shall
be rooted out on my account.” As soon as God saw David’s regret
and heard his very acceptable prayer, He commanded the angel to
desist from slaying the people, and forthwith the plague ceased
everywhere in the kingdom.[333]
From these and many other similar instances you will now observe
how full of grace and goodness David was toward all men. And just
as God saw kindliness, mercy, and humility in his heart, He saw
avarice, ferocity, and unmeasured pride in Saul’s heart; consequently
every fault was graver before God in Saul’s case than in David’s; for
the men were unlike. David was the meekest and the most merciful
of men, and whenever he fell into any fault he implored God to
spare him; but Saul grew fiercer and more envious the more sins he
fell into and the nearer he saw God’s wrath approaching. Now if you
think that these answers have led you to a clearer understanding of
the matters that you have asked about, I believe it will not be
necessary to discuss these subjects any further.
LXIV

ILLUSTRATIONS FROM THE JUDGMENTS OF SOLOMON

Son. I see clearly now from what you told in your last speech that
the judgments were lenient in David’s case, because he regretted
the sins into which he fell, but more severe in Saul’s case, because
he was less disposed to do penance for his misdeeds. Now there are
certain other matters which I am much interested in and which I
shall ask about with your permission, namely those events that
occurred after David’s death. Once when two women came before
King Solomon, quarreling about a child, the king ordered the child to
be hewn in pieces and half given to each of them:[334] now I wish to
ask whether, if neither of the women had spoken up, the king would
have hewn the child asunder or not.
Father. The king ordered the child to be divided because he knew
of a surety that the one who was the mother would not be willing to
have the child divided.
Son. I asked whether the king would have divided the child if the
mother had kept silence.
Father. If the mother had been so void of mercy that she would
not ask him to spare the child, the king would have divided it
between them.
Son. Would it not look to you like plain murder, if he had slain an
innocent child, seeing that it was not for punishment?
Father. It would indeed have been murder if he had killed the
child; still, the guilt would not have been with the king but with the
mother, if she had failed to beg mercy for her child, when she heard
the king render a fair judgment in their case, which she realized
would mean the child’s death; therefore the guilt would be hers if
she withheld the motherly pity which could save the child.
Son. What do you think about the death of Joab and Adonijah,
whom King Solomon slew? Was that a righteous judgment or not?
And why did King Solomon cause Shimei to be slain for cursing his
father David, seeing that David had already forgiven Shimei this
offence?
Father. If King Solomon had done this except as lawful
punishment, God would have visited him with a worthy penalty as
for murder. But after he had done all this, God revealed Himself to
him in a dream and bade him choose whatever gift he might wish.
But Solomon asked God to give him wisdom and insight into
righteous judgments. Then God answered him in this wise: “If this
choice were given to the multitude, there would be many who would
choose riches and power, or a long life, or peace, or success in
warfare. But because thou hast chosen this thing, thou shalt receive
what thou hast chosen and likewise all the other gifts that I have
enumerated.” From this you will observe how well God is pleased
with righteousness in judgments; for God gave Solomon all the
supreme gifts, because he chose equity as his part. And you will
understand that, if he had slain those others unjustly, God would not
have given him such excellent gifts as He did give him.
LXV

SOLOMON’S DECISION IN THE CASE OF SHIMEI

Son. What you have just said does indeed seem reasonable. If
Solomon had been led to execute these men through selfishness and
injustice, he would not have received such excellent gifts from God,
as were given to him after that deed was done. Still, if I may, I
should like to ask you to point out how righteous dooms are worked
out, in order that I may understand more clearly, and others too
who may hear it, how Solomon could execute Shimei by righteous
decree, when his father David had already forgiven him the offence.
[335]

Father. Solomon did this out of regard for justice rather than from
cruelty, and for the following reasons. When Shimei cursed David, he
did it out of impudence and malice, and for no just cause; but when
he begged David for mercy, he asked it more because of fear than of
repentance, for he was afraid that David would take his life as the
sacred law demanded. But when he implored mercy David replied in
these words: “I shall not slay you this time, since you implore my
grace; but keep in mind that you will be punished for this deed,
unless you atone in true repentance.” In these words David pointed
out to Shimei that he ought to atone with loving friendship for the
words that he had spoken in sheer hatred. Shimei, however, lived
the rest of his days in such a manner that, while no one found him
to cherish enmity toward David, it never appeared that he made
returns in friendship for David’s mercy in permitting him to live when
the law demanded his death. But when he came before Solomon
after David’s death, the king said to him: “Remember, Shimei, that
you cursed the Lord’s anointed; and it has not appeared that you
have truly regretted it since. But this shall be a covenant between us
as a reminder to repentance on your part, that you shall not enjoy
such complete freedom as one who has never fallen into this sin.
Now you have large and beautiful dwellings and many houses here
in Jerusalem and you may live in peace within the city, enjoying all
your possessions according to your desire; but if you ever go outside
the city, the punishment of the law shall come upon your head, since
you did not take thought to repent before I reminded you.” When
the king had ceased speaking, Shimei expressed himself as thankful
for this agreement and said that he should find but little
inconvenience in being forbidden to leave the city, if he might remain
secure in the king’s friendship within the city and enjoy all his
possessions. Three years later, however, Shimei forgot this
agreement and went outside the city to seek diversion,[336] as if
proud of his audacity in violating the covenant. But as soon as these
tidings were told to the king, he ordered Shimei to be seized and
brought before him, and he said to him: “You have forgotten to be
ashamed of having broken the agreement which we two made as a
reminder that you owe repentance for having cursed the Lord’s
anointed. There is, therefore, a double guilt upon your head now;
and it will be better for you to suffer a brief punishment here, so
that others may be warned by your misfortune, than that this crime
should follow you into eternal death, and others become bolder in
such evil, if you die unpunished.” Then the king ordered him to be
killed and buried outside the city as a reminder and warning to
others never to break a covenant.
LXVI

SOLOMON’S JUDGMENT IN THE CASE OF ADONIJAH AND HIS FOLLOWERS

Son. Now I wish to ask you why Solomon caused his brother
Adonijah to be put to death for requesting Abishag to be his wife.
Father. Adonijah had earlier, as you may have heard, led an
uprising against his father. When David had become an aged man
and was very decrepit because of his many years, Adonijah
appointed himself to be king without his father’s knowledge, and
made a festive banquet as newly consecrated king. He sent heralds
running through the streets with pipes and drums to proclaim
throughout the city that Adonijah was now the king. The chief men
who were with him in this plot were Joab, David’s chief captain and
his kinsman, and Abiathar the bishop, and many other lords. But
when Zadoc the bishop, Nathan the prophet, Benaiah the captain,
and Bathsheba the queen came as if in deep sorrow to tell David
what great undertakings were hidden from him, he remained silent
for some time but sighed heavily. At last he spoke as from a heart
full of grief and said: “My sons are not minded like me, for I served
King Saul many days, though he sought after my life. And yet God
had chosen me to be king, for He was angry with King Saul; but I
awaited the judgment of God by which he would be deprived of his
kingdom; but I would not condemn him, though he was mine
adversary. Now my son has done that to me which I would not do to
mine enemy. But because Adonijah has taken the kingship to which
God Himself appointed me, even before I had renounced it or He
Who had chosen me had removed me, he shall fall in disgrace from
this dignity, as that one fell who in arrogant pride raised the first
rebellion against his Lord.”
Then David said to Zadoc the bishop: “Take my mule and harness
him with all the accoutrements with which he was arrayed when I
rode him in all my glory and set my son Solomon upon him; and
taking Nathan the prophet with you and Benaiah the captain and all
my most loyal chiefs and knights, ride to the tabernacle of the Lord
in Zion[337] and there anoint my son Solomon king. Then take my
own trumpet and let it be sounded throughout the city with a festive
sound to proclaim that Solomon is king by the will of God and
David’s choice. After that you shall bring my son Solomon to me that
I may welcome the newly appointed king to my throne.” When David
had ceased speaking, Zadoc the bishop did all those things that the
king had commanded. And when Solomon returned arrayed in all the
tokens of royalty, David rose to receive him, bowed before him, and
blessed him in these words: “Praise be to Thee, O God, that Thou
wert pleased to exalt me from my low estate to such high honors as
I now enjoy, and hast helped me in many perils, and now after much
trouble and long toil hast brought me the consolation that mine eyes
should behold the one sprung from my loins whom Thou hast
Thyself chosen to sit in the seat of honor to which Thou didst
formerly appoint me, according to Thy promises, O Lord. Now I pray
Thee, O Lord, give this young man David’s glory and understanding
in double and threefold measure, make him a perfect ruler to govern
Thy holy people according to Thy will.” Then David kissed Solomon
and said to him: “The God Who rules the heavens multiply peace to
you above all the kings upon earth and give you blessings and the
fruits of earth and perfect happiness.”[338] When he had ended this
speech and benediction, David said to Solomon: “Because I find that
God has given you wisdom and understanding, I charge you to
govern wisely and justly, though somewhat severely, lest the
kingdom should seem to be lacking in government because of your
faint-heartedness. But temper the severity of punishment, lest you
be thought too stern and merciless. Remember your kinsman Joab,
however, who has served me long and with much labor; but it is not
fitting that the sinful deeds which he has committed should follow
him to hell: for he slew two excellent captains who were in my
peace, Abner and Amasa, who had served King Saul with great
fidelity. And there are many others whom he slew in his overweening
pride, but not in lawful chastisement. And it is better to let him
suffer a brief punishment here than that he should be lost eternally
because of these crimes. Keep also my promise to Shimei, though he
cursed me when I fled from the violence of your brother Absalom;
but keep it in such a way that he will be reminded to do penance for
his misdeeds, lest the curse be forever upon his head which he
incurred when he cursed me an innocent man. Let kinship temper
your wrath against your brother Adonijah, if you see that he regrets
his treasonable uprising against his father. Remember that the
bishop Abiathar lost his father and all his kinsmen, because he gave
me food, when I came to Nob a fugitive from the face of King Saul.
Abiathar deserves well for this, too, that he followed me and bore
the ark of God before me, when I fled from the face of your brother
Absalom. But do not forget to give him a reminder to repentance for
joining your brother Adonijah in treasonable designs against me, lest
this offence should follow him to his death. Be manly, strong, and
severe, but with moderation. Do the will of God in all things, and
both temporal and eternal joys shall be added to you.”[339]
Then said David to Zadoc the bishop and Nathan the prophet: “Go
now and prepare a banquet and lead King Solomon into my hall and
let him sit in my high-seat amid festive joys.” And they did
everything as David bade them. But when Adonijah’s feast was
ended, the guests heard singing and piping and all forms of
merriment, as if a new joy had come into the city. When Adonijah
asked what the merry-making signified, whether the rejoicing was in
his honor or new tidings had come, it was told him that David had
himself given Solomon his title and all the royal honors and had
chosen him to be king; and that Solomon was already hallowed as
king and sitting upon David’s throne in festive raiment; and that all
the people rejoiced in the news as on a merry holiday. When
Adonijah heard this report, great terror came upon him and all those
who were with him in this conspiracy, and they fled every man to his
house. But Adonijah fled to the tabernacle of the Lord and laid his
hand upon the sacred altar, as if taking vows of chastity and service
in God’s holy tabernacle. Thereupon he sent a man to the king,
saying: “Here shall I die, unless my lord King Solomon will promise
and assure me that he will not slay me, his servant, for the evil that
I have done.” Then King Solomon replied: “Adonijah is my brother by
kinship; therefore I will gladly spare him, if he will show true
repentance for stirring up treason and rebellion against his father
David; and I will bear this burden with him before God on the
condition that he must always continue loyal, humble, and free from
deceit. But if any treasonable ambitions be found in him, he may
expect a swift revenge to come upon his head. Let him now go
home to his possessions and enjoy them as long as he keeps what is
now decreed.”[340]
When the hour of David’s death was approaching, Solomon
frequently visited his father; and when the king had departed this
life, he mourned for him many days, he and all the lords in the
kingdom; and he buried him with every form of royal pomp and at a
vast outlay. But after David’s death, Adonijah begged Bathsheba the
queen to ask King Solomon to give him Abishag to wife. The facts
respecting Abishag were these: when King David grew old, chills
entered into his flesh, so that clothes were not sufficient to keep him
warm; Abishag was a young virgin, the fairest maid in the kingdom
and of the best and noblest family; she was brought to King David’s
bed to lie close to him and warm him and cherish him, in the hope
that the king might draw warmth from her soft and blossoming form
and from his desire for the fair virgin. David loved her highly with a
perfect affection, but as a foster-mother, not as a wife. And for this
reason Abishag won such great honor that she came to be regarded
as the first queen and she ranked above all the other queens in the
eyes of the people; and thus her dignity was sanctified by David’s
embraces. But Adonijah had a purpose in seeking this marriage after
David’s decease, for he hoped in this way to obtain the kingship by
deceitful intrigue; inasmuch as all the people would say, if he
married Abishag, that he was most worthy to sit on David’s throne
who was most worthy to mount his bed and lie in the arms which
David had hallowed with his very self. He also presumed, as seemed
reasonable, that the brothers and all the kinsmen of Abishag would
rather have him as king, if she were his, than a man who was not
bound to them in this way. Queen Bathsheba undertook Adonijah’s
errand and afterwards went to seek an interview with her son King
Solomon. As soon as she had entered the royal hall, the king rose to
meet his mother and led her to a seat at his side. Then the queen
revealed her errand, speaking thus: “I have a little favor to ask of
you, but I will not reveal the request before you promise to grant it.”
The king replied: “You are my mother, and I cannot refuse what you
wish to ask; and I surely intend that you shall have what you have
come to ask for. But it surely behooves you to keep in mind that you
should ask only for what I may freely grant.” Then said Bathsheba
the queen to the king: “I have come to ask you to give your brother
Adonijah Abishag to wife.”
Then King Solomon replied in great wrath: “What is at the bottom
of this request that Abishag be given to Adonijah? If you prefer that
he should have the kingship rather than I, then ask the kingdom for
him; for you know that my brother Adonijah is older than I and once
assumed the royal title, being chosen by the chief lords before my
father had appointed me to be ruler in obedience to the will of God.
Joab the most powerful of the lords and captains and Abiathar the
bishop have evidently continued plotting with him even to this day.
Abishag is of the noblest kinship in the city and the whole realm;
furthermore, she is honored by all as the first queen because of the
care that she gave my father in his old age. If she is given to
Adonijah to be his wife, the people will regard him as most worthy to
sit in David’s seat, since he is thought worthy to lie in the bed and in
the arms in which David himself lay. Now when Adonijah had
committed treason against his father, I offered to share the
responsibility for his sin before God because of our kinship. But now
he has repeated and trebled the treason against me, his brother,
which he first committed against his father. Therefore I swear by the
God Who has placed me on David’s throne that Adonijah shall suffer
for his guilt, as shall every one of the others who are with him in this
traitorous project.” Then King Solomon said to Benaiah the captain:
“Go and slay my brother Adonijah, for I would rather have him suffer
a swift penalty here, such as the rules of the holy law provide for
treason against one’s lord, than to have him carry a traitor’s guilt to
hell. Slay also Joab my kinsman, for twice he committed vile
offences against King David, when he slew Abner and Amasa, two
renowned captains, though they were in David’s peace and
protection. But his third and greatest crime is this, that he was
traitor to David when he gave Adonijah the royal title; surely he will
be lost forever in the world to come, unless he shall do penance in
this world by suffering a lawful punishment.”[341]
In this case King Solomon gives clear proof that it is quite
permissible to break vows and promises, if what has been asked or
granted is contrary to what is right. He granted what his mother
Bathsheba the queen had come to request before he knew what it
was; but as soon as he was aware that the prayer was a perilous
one, he slew the man who had originally made the request. Benaiah
did as King Solomon commanded and slew Adonijah. But just as
Joab the captain and Abiathar the bishop had shared in the plans to
give Adonijah the royal title, they also had a share in his plan to ask
for Abishag to wife; and when they heard of Adonijah’s death, they
foresaw their own destruction. Benaiah seized Abiathar the bishop
and led him before King Solomon; but Joab fled to God’s tabernacle
and laid his hand upon the sacred horn of the altar, as if taking vows
of chastity and service in God’s holy tabernacle. Benaiah came to
God’s sanctuary and said: “Come forth, Joab, the king commands
you to come forth out of God’s tabernacle.” But Joab replied: “I have
come hither into God’s protection, and I will suffer death here, if I
cannot remain in security.” Then Benaiah reported his answer to the
king through his messenger; and when the messenger came before
the king bringing the bishop Abiathar and related all these things,
King Solomon said to him: “Give my command to Benaiah to slay
Joab wherever he be found, for his deeds and the decrees of the
sacred law slay him and not we.” Benaiah did as King Solomon
commanded and slew Joab where he then stood.[342]
But the king spoke in this wise to the bishop Abiathar: “You know
that you have deserved death according to the rules of the holy law;
but whereas you lost your father and all your kinsmen in Nob in a
single day, because your father had given my father David food, and
whereas you also bore the ark of God before my father when he fled
before the face of my brother Absalom, therefore it is right that for
once you should profit from this and not suffer a sudden death. And
for this once you shall purchase your life on the following terms,
which you must keep as a constant reminder that you owe penance
for the treason which you committed against David: go now to your
own fields and abide there as a husbandman and enjoy all your
possessions, on the condition, however, that you remain a tiller of
the soil. But if you ever stretch forth your hand to perform any
priestly service or office, the righteous penalty of the sacred law
shall surely come upon your head.”[343] Abiathar went home and did
as the king commanded and lived many days; but Shimei died three
years later, because he failed to keep what had been commanded,
as we have already told.

You might also like