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

Reactive Programming with Kotlin First Edition Learn Rx with RxJava RxKotlin and RXAndroid Alex Sullivan download

The document provides information about the book 'Reactive Programming with Kotlin' by Alex Sullivan, which focuses on learning reactive programming using RxJava, RxKotlin, and RxAndroid. It includes links to download the book and other related resources, as well as acknowledgments and details about the authors and editors involved in the publication. The table of contents outlines the structure of the book, covering topics from getting started with RxJava to advanced practices and community contributions.

Uploaded by

glaveawwadfh
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 (4 votes)
31 views

Reactive Programming with Kotlin First Edition Learn Rx with RxJava RxKotlin and RXAndroid Alex Sullivan download

The document provides information about the book 'Reactive Programming with Kotlin' by Alex Sullivan, which focuses on learning reactive programming using RxJava, RxKotlin, and RxAndroid. It includes links to download the book and other related resources, as well as acknowledgments and details about the authors and editors involved in the publication. The table of contents outlines the structure of the book, covering topics from getting started with RxJava to advanced practices and community contributions.

Uploaded by

glaveawwadfh
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/ 69

Reactive Programming with Kotlin First Edition

Learn Rx with RxJava RxKotlin and RXAndroid Alex


Sullivan pdf download

https://textbookfull.com/product/reactive-programming-with-
kotlin-first-edition-learn-rx-with-rxjava-rxkotlin-and-rxandroid-
alex-sullivan/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Reactive Programming with RxJava Creating Asynchronous


Event Based Applications 1st Edition Tomasz Nurkiewicz
Ben Christensen

https://textbookfull.com/product/reactive-programming-with-
rxjava-creating-asynchronous-event-based-applications-1st-
edition-tomasz-nurkiewicz-ben-christensen/

Reactive Programming with Angular and ngrx: Learn to


Harness the Power of Reactive Programming with RxJS and
ngrx Extensions 1st Edition Oren Farhi (Auth.)

https://textbookfull.com/product/reactive-programming-with-
angular-and-ngrx-learn-to-harness-the-power-of-reactive-
programming-with-rxjs-and-ngrx-extensions-1st-edition-oren-farhi-
auth/

Kotlin Apprentice Second Edition Beginning Programming


with Kotlin Irina Galata

https://textbookfull.com/product/kotlin-apprentice-second-
edition-beginning-programming-with-kotlin-irina-galata/

Reactive Programming with JavaScript 1st Edition


Hayward Jonathan

https://textbookfull.com/product/reactive-programming-with-
javascript-1st-edition-hayward-jonathan/
Programming Kotlin Applications Building Mobile and
Server Side Applications with Kotlin 1st Edition Brett
Mclaughlin

https://textbookfull.com/product/programming-kotlin-applications-
building-mobile-and-server-side-applications-with-kotlin-1st-
edition-brett-mclaughlin/

Programming Android With Kotlin: Achieving Structured


Concurrency With Coroutines Pierre-Olivier Laurence

https://textbookfull.com/product/programming-android-with-kotlin-
achieving-structured-concurrency-with-coroutines-pierre-olivier-
laurence/

RxSwift Reactive Programming with Swift 1st Edition


Florent Pillet

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

RxSwift Reactive Programming with Swift Third Edition


Raywenderlich Tutorial Team

https://textbookfull.com/product/rxswift-reactive-programming-
with-swift-third-edition-raywenderlich-tutorial-team/

Scala Reactive Programming Build scalable functional


reactive microservices with Akka Play and Lagom 1st
Edition Rambabu Posa

https://textbookfull.com/product/scala-reactive-programming-
build-scalable-functional-reactive-microservices-with-akka-play-
and-lagom-1st-edition-rambabu-posa/
Reactive Programming with Kotlin

Reactive Programming with Kotlin


By Alex Sullivan

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
Reactive Programming with Kotlin

Dedications
"To my wonderful partner Pallavi, without whom I would have never
been able to start this undertaking. Your support and encouragement
mean the world to me."

— Alex Sullivan

raywenderlich.com 3
Reactive Programming with Kotlin

About the Author


Alex Sullivan is an author of this book. Alex is a mobile developer
who works at Thoughtbot in Boston, where he enjoys reactive
programming, experimenting with different programming languages,
and tinkering with fun approaches to building mobile applications. In
his spare time, Alex enjoys traveling and relaxing with his partner,
binging unhealthy amounts of Netflix and reading. Alex hopes to one
day find a cat he's not allergic to and rant about bracket placement to
him or her.

About the Editors


Joe Howard is the final pass editor for this book. Joe is a former
physicist that studied computational particle physics using parallel
Fortran simulations. He gradually shifted into systems engineering
and then ultimately software engineering around the time of the
release of the iOS and Android SDKs. He's been a mobile software
developer on iOS and Android since 2009, working primarily at two
agencies in Boston, MA since 2011. He's now the Pillar Lead for
raywenderlich.com. Twitter: @orionthewake.

Vijay Sharma is the final pass editor of this book. Vijay is a husband,
a father and a senior mobile engineer. Based out of Canada's capital,
Vijay has worked on dozens of apps for both Android and iOS. When
not in front of his laptop, you can find him in front of a TV, behind a
book, or chasing after his kids. You can reach out to him on Twitter
@vijaysharm or on LinkedIn @vijaysharm

Manda Frederick is the editor of this book. She has been involved in
publishing for over ten years through various creative, educational,
medical and technical print and digital publications, and is thrilled to
bring her experience to the raywenderlich.com family as Managing
Editor. In her free time, you can find her at the climbing gym,
backpacking in the backcountry, hanging with her dog, working on
poems, playing guitar and exploring breweries.

raywenderlich.com 4
Reactive Programming with Kotlin

Victoria Gonda is a tech editor for this book. Victoria is a software


developer working mostly on Android apps. When she's not traveling
to speak at conferences, she works remotely from Chicago. Her
interest in tech started while studying computer science and dance
production in college. In her spare time, you can find Victoria
relaxing with a book, her partner, and her pets. You can connect with
her on Twitter at @TTGonda.

Ellen Shapiro is a tech editor for this book. Ellen is an iOS developer
for Bakken & Bæck's Amsterdam office who also occasionally writes
Android apps. She has worked in her spare time to help bring iOS
songwriting app Hum to life. She’s also developed several
independent applications through her personal company, Designated
Nerd Software. When she's not writing code, she's usually tweeting
about it at @DesignatedNerd.

Amanjeet Singh is a tech editor for this book. Amanjeet is an


Android Engineer in Delhi, India and an open source enthusiast. As a
developer he always tries to build apps with optimized performance
and good architectures which can be used on a large scale. Currently
Android Engineer at 1mg, he helps in building apps for one of the
leading healthcare platform in India. Also a technical editor and
author in android team at raywenderlich.com.

Matei Suica is a tech editor for this book. Matei is a software


developer that dreams about changing the world with his work. From
his small office in Romania, Matei is trying to create an App that will
help millions. When the laptop lid closes, he likes to go to the gym
and read. You can find him on Twitter or LinkedIn: @mateisuica

raywenderlich.com 5
Reactive Programming with Kotlin

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 6
Reactive Programming with Kotlin

Acknowldegments
We'd also like to thank the RxSwift: Reactive Programming with Swift authors, whose
work served as the basis for parts of this book:
• Scott Gardner has been developing iOS apps since 2010, Swift since the day it was
announced, and RxSwift since before version 1. He's authored several video courses,
tutorials, and articles on iOS app development, presented at numerous conferences,
meetups, and online events, and this is his second book. Say hello to Scott on Twitter
at @scotteg.
• Junior Bontognali has been developing on iOS since the first iPhone and joined the
RxSwift team in the early development stage. Based in Switzerland, when he's not
eating cheese or chocolate, he's doing some cool stuff in the mobile space, without
denying to work on other technologies. Other than that he organizes tech events,
speaks and blogs. Say hello to Junior on Twitter at @bontoJR.
• Florent Pillet has been developing for mobile platforms since the last century and
moved to iOS on day 1. He adopted reactive programming before Swift was
announced and has been using RxSwift in production since 2015. A freelance
developer, Florent also uses Rx on Android and likes working on tools for developers
like the popular NSLogger when he's not contracting for clients worldwide. Say hello
to Florent on Twitter at @fpillet.
• Marin Todorov is one of the founding members of the raywenderlich.com team and
has worked on seven of the team's books. Besides crafting code, Marin also enjoys
blogging, teaching, and speaking at conferences. He happily open-sources code. You
can find out more about Marin at www.underplot.com.

raywenderlich.com 7
Reactive Programming with Kotlin

Table of Contents: Overview


Book License ........................................................... 18
Book Source Code & Forums ................................... 19
What You Need ....................................................... 20
Book Updates .......................................................... 21
About the Cover....................................................... 22
Section I: Getting Started with RxJava .................... 23
Chapter 1: Hello, RxJava! .................................. 24
Chapter 2: Observables .................................... 45
Chapter 3: Subjects .......................................... 63
Chapter 4: Observables & Subjects in Practice 79
Section II: Operators & Best Practices ................... 100
Chapter 5: Filtering Operators ......................... 102
Chapter 6: Filtering Operators in Practice ....... 120
Chapter 7: Transforming Operators ................. 133
Chapter 8: Transforming Operators in
Practice ........................................................... 149
Chapter 9: Combining Operators .................... 163
Chapter 10: Combining Operators in Practice . 185
Chapter 11: Time-Based Operators ................ 203
Section III: Intermediate RxJava ............................ 223

raywenderlich.com 8
Reactive Programming with Kotlin

Chapter 12: Error Handling in Practice ............ 224


Chapter 13: Intro to Schedulers ...................... 244
Chapter 14: Flowables & Backpressure .......... 262
Chapter 15: Testing RxJava Code ................... 277
Chapter 16: Creating Custom Reactive
Extensions ...................................................... 294
Section IV: RxJava Community Cookbook ............. 311
Chapter 17: RxBindings ................................... 312
Chapter 18: Retrofit ......................................... 331
Chapter 19: RxPreferences ............................. 349
Chapter 20: RxPermissions ............................ 363
Section V: Putting It All Together ........................... 377
Chapter 21: RxJava & Jetpack ........................ 378
Chapter 22: Building a Complete RxJava App 395
Conclusion ............................................................ 423

raywenderlich.com 9
Reactive Programming with Kotlin

Table of Contents: Extended


Book License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Book Source Code & Forums . . . . . . . . . . . . . . . . . . . . . . 19
What You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Book Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
About the Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Section I: Getting Started with RxJava . . . . . . . . . . . . . 23
Chapter 1: Hello, RxJava! . . . . . . . . . . . . . . . . . . . . . . . . . 24
RxJava and RxKotlin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Introduction to asynchronous programming . . . . . . . . . . . . . . . . . . . . 26
Foundations of RxJava . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
App architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
RxAndroid and RxBinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Installing RxJava . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Chapter 2: Observables . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
What is an observable? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Lifecycle of an observable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Creating observables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Subscribing to observables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Disposing and terminating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
The create operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Creating observable factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Using other observable types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

raywenderlich.com 10
Reactive Programming with Kotlin

Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Chapter 3: Subjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
What are subjects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Working with publish subjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Working with behavior subjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Working with replay subjects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Working with async subjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Working with the RxRelay library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Chapter 4: Observables & Subjects in Practice . . . . 79


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Using a BehaviorSubject in a ViewModel . . . . . . . . . . . . . . . . . . . . . . . 81
Adding photos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Communicating with other views via subjects . . . . . . . . . . . . . . . . . . . 87
Creating a custom observable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Review: Single, Maybe, Completable . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Using Single in the app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Section II: Operators & Best Practices . . . . . . . . . . . . 100


Chapter 5: Filtering Operators . . . . . . . . . . . . . . . . . . . 102
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Ignoring operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Skipping operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Taking operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Distinct operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Challenge: Create a phone number lookup . . . . . . . . . . . . . . . . . . . . . 117
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

raywenderlich.com 11
Reactive Programming with Kotlin

Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Chapter 6: Filtering Operators in Practice . . . . . . . . . 120


Improving the Combinestagram project . . . . . . . . . . . . . . . . . . . . . . . 121
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Key points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

Chapter 7: Transforming Operators . . . . . . . . . . . . . . . 133


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Transforming elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Transforming inner observables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Observing events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Key points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

Chapter 8: Transforming Operators in Practice . . . . 149


Getting started with GitFeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Fetching data from the web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Transforming the response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Processing the response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Persisting objects to disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Adding a last-modified header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Key points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Chapter 9: Combining Operators . . . . . . . . . . . . . . . . 163


Getting started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Prefixing and concatenating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Merging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Combining elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

raywenderlich.com 12
Reactive Programming with Kotlin

Combining elements within a sequence . . . . . . . . . . . . . . . . . . . . . . . 180


Challenge: The zip case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

Chapter 10: Combining Operators in Practice . . . . . 185


Getting started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Preparing the EONET API class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Add events into the mix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Combining events and categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Downloading in parallel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Wiring up the days seek bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Challenge: Adding a progress bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202

Chapter 11: Time-Based Operators . . . . . . . . . . . . . . 203


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Buffering operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Time-shifting operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Timer operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

Section III: Intermediate RxJava . . . . . . . . . . . . . . . . . . 223


Chapter 12: Error Handling in Practice . . . . . . . . . . . . 224
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Managing errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Handle errors with catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Catching errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Retrying on error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Errors as objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

raywenderlich.com 13
Reactive Programming with Kotlin

Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Chapter 13: Intro to Schedulers . . . . . . . . . . . . . . . . . . 244


What is a scheduler? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Setting up the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Switching schedulers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Best practices and built-in schedulers . . . . . . . . . . . . . . . . . . . . . . . . 257
Key points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261

Chapter 14: Flowables & Backpressure. . . . . . . . . . . 262


Backpressure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Buffering danger! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Natural backpressure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Introduction to Flowables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Backpressure strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Flowables, Observables, Processors and Subjects — Oh, My! . . . . . 272
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

Chapter 15: Testing RxJava Code . . . . . . . . . . . . . . . . 277


Getting started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Introduction to TestObserver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Using a TestScheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Injecting schedulers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Using Trampoline scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Using subjects with mocked data. . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Testing ColorViewModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293

Chapter 16: Creating Custom Reactive


Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294

raywenderlich.com 14
Reactive Programming with Kotlin

Extending a framework class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296


Wiring the extension up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Wrapping the locations API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
The lift and compose functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Testing your custom reactive extension . . . . . . . . . . . . . . . . . . . . . . . 307
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310

Section IV: RxJava Community Cookbook . . . . . . . . 311


Chapter 17: RxBindings . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Extending ValueAnimator to be reactive . . . . . . . . . . . . . . . . . . . . . . . 314
Using RxBindings with Android widgets . . . . . . . . . . . . . . . . . . . . . . . 315
Fetching colors from an API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Displaying an information dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330

Chapter 18: Retrofit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Recap of Retrofit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Including Rx adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Creating a JSON object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Updating the JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Retrieving JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

Chapter 19: RxPreferences . . . . . . . . . . . . . . . . . . . . . . 349


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Using SharedPreferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Listening for preference updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Using RxPreferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355

raywenderlich.com 15
Reactive Programming with Kotlin

Subscribing to preference changes . . . . . . . . . . . . . . . . . . . . . . . . . . 356


Saving custom objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

Chapter 20: RxPermissions . . . . . . . . . . . . . . . . . . . . . 363


Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Requesting the location permission . . . . . . . . . . . . . . . . . . . . . . . . . . 365
Using RxPermissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Requesting another permission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Reading from external storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Writing the weather to external storage . . . . . . . . . . . . . . . . . . . . . . . 372
Reacting to orientation changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376

Section V: Putting It All Together . . . . . . . . . . . . . . . . . 377


Chapter 21: RxJava & Jetpack . . . . . . . . . . . . . . . . . . . 378
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
RxJava and Room . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Reacting to database changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Updating individual items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Starting the app with cached data . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Paging data in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394

Chapter 22: Building a Complete RxJava App . . . . 395


Introducing QuickTodo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
Architecting the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Task model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Task Dao . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
Task repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Replacing callbacks with observables . . . . . . . . . . . . . . . . . . . . . . . . 409

raywenderlich.com 16
Reactive Programming with Kotlin

Editing tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412


Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423

raywenderlich.com 17
L Book License

By purchasing Reactive Programming with Kotlin, you have the following license:

• You are allowed to use and/or modify the source code in Reactive Programming with
Kotlin 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
Reactive Programming with Kotlin in as many apps as you want, but must include this
attribution line somewhere inside your app: “Artwork/images/designs: from Reactive
Programming with Kotlin, available at www.raywenderlich.com”.

• The source code included in Reactive Programming with Kotlin is for your personal use
only. You are NOT allowed to distribute or sell the source code in Reactive
Programming with Kotlin 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 18
B Book Source Code &
Forums

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 from
https://store.raywenderlich.com/products/reactive-programming-with-kotlin.

We’ve also set up an official forum for the book at forums.raywenderlich.com. This is a
great place to ask questions about the book or to submit any errors you may find.

raywenderlich.com 19
W What You Need

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

• A PC running Windows 10 or a recent Linux such as Ubuntu 18.04 LTS, or a


Mac running the latest point release of macOS Mojave or later: You’ll need one
of these to be able to install the latest versions of IntelliJ IDEA and Android Studio.

• IntelliJ IDEA Community 2019.1 or later: IntelliJ IDEA is the IDE upon which
Android Studio is based, and it's used in the book to look at pure Kotlin projects that
demonstrate techniques in RxJava. You can download the latest version of IntelliJ
IDEA Community for free here: https://www.jetbrains.com/idea/

• JDK 8 or later: You'll need a Java Development Kit installed for use with IntelliJ
IDEA projects (Android Studio will use its own version of the JDK). You can download
the Oracle JDK from here: https://www.oracle.com/technetwork/java/javase/
downloads/index.html

• Android Studio 3.3.2 or later: Android Studio is the main development tool for
Android. You can download the latest version of Android Studio for free here:
https://developer.android.com/studio

• An intermediate level knowledge of Kotlin and Android development. This book is


about learning RxJava specifically; to understand the rest of the project code and
how the accompanying demo projects work you will need at least an intermediate
understanding of Kotlin and the Android SDK.

All the Android sample projects in this book will work just fine in an Android emulator
bundled with Android Studio, or you can also use a physical Android device.

raywenderlich.com 20
B Book Updates

Since you’ve purchased the digital edition version of this book, you get free access to
any updates we may make to the book!

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 iOS
development links for that month. You can sign up here:

• www.raywenderlich.com/newsletter

raywenderlich.com 21
A About the Cover

The common starling, pictured on the cover of this book, seems just that: common. It
isn't particularly large — roughly only 8 inches long. It isn't particularly musical and is
considered noisy in flocks and communal roosts. It's also not particularly beautiful,
with dark glossy feathers and a subtle metallic sheen.

And, yet, this simple bird continues to hold our attention, even being referenced in
literature as early as Shakespeare. Why?

First, it has a talent for mimicry and, like the reactive sensibilities explored in this book,
is highly responsive to its environment. It has up to 20 distinct imitations of other
birds, and it is even known to mimic ringing phones and car alarms.

And, most impressively, a flock of starlings in flight is a gorgeous display of reactivity


in motion. You've probably seen it, yourself: thousands of birds creating fluid shapes —
called murmurations — in the air, never pausing, each bird responding to the next.

While we can't know how these birds evolved to this level of cooperation and
responsiveness, we hope to draw some inspiration from them in this book as we guide
you through developing your own reactive programming.

You can learn more about these birds, here: https://en.wikipedia.org/wiki/


Common_starling.

See them in flight, here: https://video.nationalgeographic.com/video/short-film-


showcase/00000158-457d-d0be-a1dc-4f7f8e650000.

raywenderlich.com 22
Section I: Getting Started with
RxJava

In this part of the book, you’re going to learn about the basics of RxJava. You are going
to have a look at what kinds of asynchronous programming problems RxJava addresses,
and what kind of solutions it offers.

Further, you will learn about the few basic classes that allow you to create and observe
event sequences, which are the foundation of the Rx framework.

You are going to start slow by learning about the basics and a little bit of theory. Please
don't skip these chapters! This will allow you to make good progress in the following
sections when things get more complex.

Chapter 1: Hello, RxJava!

Chapter 2: Observables

Chapter 3: Subjects

Chapter 4: Observables & Subjects in Practice

raywenderlich.com 23
1 Chapter 1: Hello, RxJava!
By Alex Sullivan & Marin Todorov

This book aims to introduce you, the reader, to the RxJava, RxKotlin and RxAndroid
libraries and to writing reactive Android apps with Kotlin.

RxJava and RxKotlin


You may be asking yourself "Wait, why am I reading about RxJava when I'm using Kotlin
to build Android apps?" Great question! RxJava has been around since 2013, well before
Kotlin began to be accepted as a mainstream programming language, and is part of a
long list of Rx-based libraries written for different platforms and systems. Since Kotlin
has such excellent interopability with Java, it wouldn't make sense to completely
rewrite RxJava for Kotlin — you can just use the existing RxJava library instead!

However, just because RxJava doesn't need to be completely rewritten to work in Kotlin
doesn't mean that it couldn't benefit from all of the great features in the Kotlin
programming language.

That's where RxKotlin comes into play. RxKotlin is a library that expands RxJava by
adding a ton of utilities and extension methods that make working with RxJava much
more pleasant in Kotlin. However, you absolutely do not need RxKotlin to use the
RxJava library in a Kotlin-based Android app.

But what exactly is RxJava? Here’s a good definition:

RxJava is a library for composing asynchronous and event-based code by using


observable sequences and functional style operators, allowing for parameterized
execution via schedulers.

raywenderlich.com 24
Reactive Programming with Kotlin Chapter 1: Hello, RxJava!

Sound complicated? Don’t worry if it does. Writing reactive programs, understanding


the many concepts behind them and navigating a lot of the relevant, commonly used
lingo might be intimidating — especially if you try to take it all in at once, or when you
haven’t been introduced to it in a structured way.

That’s the goal of this book: to gradually introduce you to the various RxJava APIs and
Rx concepts by explaining how to use each of the APIs, and then covering their
practical usage in Android apps.

You’ll start with the basic features of RxJava, and then gradually work through
intermediate and advanced topics. Taking the time to exercise new concepts
extensively as you progress will make it easier to master RxJava by the end of the book.
Rx is too broad of a topic to cover completely in a single book; instead, we aim to give
you a solid understanding of the library so that you can continue developing Rx skills
on your own.

We still haven’t quite established what RxJava is though, have we? Start with a simple,
understandable definition and progress to a better, more expressive one as we waltz
through the topic of reactive programming later in this chapter.

RxJava, in its essence, simplifies developing asynchronous programs by allowing your


code to react to new data and process it in a sequential, isolated manner. In other
words, RxJava lets you observe sequences of asynchronous events in an app and
respond to each event accordingly. Examples are taps by a user on the screen and
listening for the results of asynchronous network calls.

As an Android app developer, this should be much more clear and tell you more about
what RxJava is, compared to the first definition you read earlier in this chapter.

Even if you’re still fuzzy on the details, it should be clear that RxJava helps you write
asynchronous code. And you know that developing good, deterministic, asynchronous
code is hard, so any help is quite welcome!

raywenderlich.com 25
Reactive Programming with Kotlin Chapter 1: Hello, RxJava!

Introduction to asynchronous
programming
If you tried to explain asynchronous programming in a simple, down-to-earth
language, you might come up with something along the lines of the following:

An Android app, at any moment, might be doing any of the following things and more:

• Reacting to button taps

• Animating a view across the screen

• Downloading a large photo from the internet

• Saving bits of data to disk

• Playing audio

All of these things seemingly happen at the same time. Whenever the keyboard
animates out of the screen, the audio in your app doesn’t pause until the animation has
finished, right?

All the different bits of your program don’t block each other’s execution. Android offers
you several different APIs that allow you to perform different pieces of work on
different threads and perform them across the different cores of the device’s CPU.

Writing code that truly runs in parallel, however, is rather complex, especially when
different bits of code need to work with the same pieces of data. It’s hard to determine
which piece of code updates the data first or which code has read the latest value.

Android asynchronous APIs


Google has provided several different APIs that help you write asynchronous code.
You've probably used a few of them before, and chances are they left you leaving a bit
frustrated or maybe even scared.

You’ve probably used at least one of the following:

• AsyncTask: To do some work on the background and then update elements in your UI
with the result of that background work. You have to make sure to properly handle
cancelling a running AsyncTask when your Activity or Fragment shuts down, since
you could otherwise get a NullPointerException when the AsyncTask tries to update
UI elements that don't exist anymore.

raywenderlich.com 26
Reactive Programming with Kotlin Chapter 1: Hello, RxJava!

• IntentService: To start a fire-and-forget background job using an Intent. You


typically use an IntentService if you want to do some work that doesn't need to
touch the UI at all — saving an object to a database, for example.

• Thread: To start background work in a purely Java way without interacting with any
Android APIs. Threads come with the downside of being expensive and not bound to
any sort of ThreadPool.

• Future: To clearly chain work which will complete at some undetermined point in
the future. Futures are considerably clearer to use than AsyncTasks, but run into
some of the same problems around null pointers when a Fragment or Activity has
been destroyed.

The above isn't an exhaustive list — there's also Handler, JobScheduler, WorkManager,
HandlerThread and Kotlin coroutines.

Coroutines and RxJava


Now that Kotlin coroutines have started to become popular in the Android
development world, you may be asking yourself if it's still worthwhile to learn about
RxJava.

Many comparisons have been made between using RxJava and using coroutines for
Android development. Each review will give you a different answer about which tool
you should use.

In reality, RxJava and coroutines work at different levels of abstractions. Coroutines


offer a more lightweight approach to threading and allow you to write asynchronous
code in a synchronous manner. Rx, on the other hand, is used primarily to create the
event-driven architecture mentioned above, and to allow you to write reactive
applications. So, while they both offer an answer for doing asynchronous work off the
main thread, they're really different tools that are both useful depending on the
context.

If you're simply looking for an easy way to replace AsyncTask, then coroutines may
make more sense than pulling RxJava into your application. However, if you do want to
move towards a reactive, event-driven architecture, then RxJava is your best bet!

Asynchronous programming challenges


Since most of your typical classes would do something asynchronously, and all UI
components are inherently asynchronous, it’s impossible to make assumptions in what
order the entirety of your app code will get executed.

raywenderlich.com 27
Reactive Programming with Kotlin Chapter 1: Hello, RxJava!

After all, your app’s code runs differently depending on various external factors, such as
user input, network activity, or other OS events. Each time the user fires up your app,
the code may run in a completely different order depending on those external factors.
(Well, except for the case when you have an army of robots testing your app, then you
can expect all events to happen with precise, kill-bot synchronization.)

We’re definitely not saying that writing good asynchronous code is impossible. After all,
there's a litany of tools — like the ones listed above — that Android developers have
been using to write asynchronous apps since well before RxJava hit the scene.

The issue is that complex asynchronous code becomes very difficult to write in part
because of the variety of APIs that you as an Android developer will end up using:

You may be using an AsyncTask to update your UI, an IntentService to save something
to a database, a WorkManager task to sync your app to a server, and other various
asynchronous APIs. Since there is no universal language across all the asynchronous
APIs, reading and understanding the code, and reasoning about its execution, becomes
difficult.

To wrap up this section and put the discussion into a bit more context, you’ll compare
two pieces of code: one synchronous and one asynchronous.

Synchronous code
Performing an operation for each element of a list is something you’ve done plenty of
times. It’s a very simple yet solid building block of app logic because it guarantees two
things: It executes synchronously, and the collection is immutable from the outside
world while you iterate over it.

raywenderlich.com 28
Reactive Programming with Kotlin Chapter 1: Hello, RxJava!

Take a moment to think about what this implies. When you iterate over a collection,
you don’t need to check that all elements are still there, and you don’t need to rewind
back in case another thread inserts an element at the start of the collection. You
assume you always iterate over the collection in its entirety at the beginning of the loop.

If you want to play a bit more with these aspects of the for loop, try this in an app or
IntelliJ IDEA project:

var list = listOf(1, 2, 3)


for (number in list) {
println(number)
list = listOf(4, 5, 6)
}
print(list)

Is list mutable inside the for body? Does the collection that the loop iterates over ever
change? What’s the sequence of execution of all commands? Can you modify number if
you need to? You may be surprised by what you see if you run this code.

Asynchronous code
Consider similar code, but assume each iteration happens as a reaction to a click on a
button. As the user repeatedly clicks on the button, the app prints out the next element
in a list:

var list = listOf(1, 2, 3)


var currentIndex = 0
button.setOnClickListener {
println(list[currentIndex])

if (currentIndex != list.lastIndex) {
currentIndex++
}
}

Think about this code in the same context as you did for the previous one. As the user
clicks the button, will that print all of the list's elements? You really can’t say. Another
piece of asynchronous code might remove the last element, before it’s been printed.

Or another piece of code might insert a new element at the start of the collection after
you’ve moved on.

Also, you assume only that the click listener will ever change currentIndex, but another
piece of code might modify currentIndex as well — perhaps some clever code you
added at some point after crafting the above function.

You’ve likely realized that some of the core issues with writing asynchronous code are:
a) the order in which pieces of work are performed and b) shared mutable data.

raywenderlich.com 29
Discovering Diverse Content Through
Random Scribd Documents
sides face the cardinal points, it rose in four equal stories to a height
of nearly two hundred feet, having a summit platform of about two
hundred feet square.[IX-13] Humboldt in 1803 found the four terraces
tolerably distinct, especially on the western slope; Evans in 1870
found the lower terrace quite perfect, but the others traceable only
in a few places without excavation.
The material of which the mound was constructed is adobes, or sun-
dried bricks, generally about fifteen inches long, laid very regularly
with alternate layers of clay. From its material comes the name
Tlalchihualtepec, 'mountain of unburnt bricks,' which has been
sometimes applied to Cholula. An old tradition relates that the
adobes were manufactured at Tlalmanalco, and brought several
leagues to their destination by a long line of men, who handed them
along singly from one to another. Humboldt thought some of the
bricks might have been slightly burned. Respecting the material
which constitutes the alternate layers between the bricks, called clay
by Humboldt, there seems to be some difference of opinion between
different explorers. Col. Brantz Mayer, a careful investigator, says the
adobes are interspersed with small fragments of porphyry and
limestone; and Mr Tylor speaks of them as cemented with mortar
containing small stones and pottery. Evans tells us that the material
is adobe bricks and layers of lava, still perfect in many places. The
historian Veytia by a personal examination ascertained the material
to be "small stones of the kind called guijarros, and a kind of bricks
of clay and straw," in alternate layers.[IX-14] Beaufoy claims to have
found the pyramid faced with small thin hewn stones, one of which
he carried away as a relic—a very wonderful discovery certainly,
when we consider that other very trustworthy explorers, both
preceding and following Beaufoy, found nothing of the kind. Mr
Heller could not find the stone facing, but, as he says, he did find a
coating of mortar as hard as stone, composed of lime, sand, and
water.[IX-15] Many visitors have believed that the pyramid is only
partially artificial, the adobe-work having been added to a smaller
natural hill. This is, however, a mere conjecture, and there are
absolutely no arguments to be adduced for or against it. The truth
can be ascertained only by the excavation of a tunnel through the
mound at its base, or, at least, penetrating to the centre. It is very
remarkable that such an excavation has never been made, either in
the interests of scientific exploration or of treasure-seeking.
Bernal Diaz, at the time of the Conquest, counted a hundred and
twenty steps in a stairway which led up the slope to the temple, but
no traces of such a stairway have been visible in more modern
times. There are traditions among the natives, as is usually the case
in connection with every work of the antiguos, of interior galleries
and apartments of great extent within the mound; such rumors are
doubtless without foundation. The Puebla road cuts off a corner of
the lower terrace, and the excavation made in building the road not
only showed clearly the regular interior construction of the pyramid,
but also laid bare a tomb, which contained two skeletons with two
idols in basalt, a collection of pottery, and other relics not preserved
or particularly described, although the remains of the tomb itself
were examined by Humboldt. The sepulchre was square, with stone
walls supported by cypress beams. The dimensions are not given,
but the apartment is said to have had no traces of any outlet.
Humboldt claims to have discovered a peculiar arrangement of the
adobes about this tomb, by which the pressure on its roof was
diminished.
It is very evident that the pyramid of Cholula contains nothing in
itself to indicate its age, but from well-defined and doubtless reliable
traditions, we may feel very sure that its erection dates back to an
epoch preceding the tenth century, and probably preceding the
seventh. Humboldt shows that it is larger at the base than any of the
old-world pyramids, over twice as large as that of Cheops, but only
slightly higher than that of Mycerinus. "The construction of the
teocalli recalls the oldest monuments to which the history of the
civilization of our race reaches. The temple of Jupiter Bélus, which
the mythology of the Hindus seems to designate by the name of
Bali, the pyramids of Meïdoùm and Dahchoùr, and several of the
group of Sakharah in Egypt, were also immense heaps of bricks, the
remains of which have been preserved during a period of thirty
centuries down to our day."[IX-16]
The historical annals of aboriginal times, confirmed by the Spanish
records of the Conquest, leave no doubt that the chief object of the
pyramid was to support a temple; the discovery of the tomb with
human remains may indicate that it served also for burial purposes.
It is by no means certain, however, that the mound was in any sense
a monument reared over the two bodies whose skeletons were
found; for besides the position of the skeletons in a corner of the
pyramid, indicating in itself the contrary, there is the possibility that
the bodies were those of slaves sacrificed during the process of
building, and deposited here from some superstitious motive. It will
require the discovery of tombs near the centre of this immense
mound to prove that it was erected with any view to use as the
burial place of kings or priests.[IX-17] Wilson, always a sceptic on
matters connected with Mexican aboriginal civilization, pronounces
the pyramid of Cholula "the finest Indian mound on this continent;
where the Indians buried the bravest of their braves, with bows and
arrows, and a drinking cup, that they might not be unprovided for
when they should arrive at the hunting-grounds of the great spirit."
"It is sufficiently wasted by time to give full scope to the imagination
to fill out or restore it to almost any form. One hundred years ago,
some rich citizen constructed steps up its side, and protected the
sides of his steps from falling earth by walls of adobe, or mud-brick;
and on the west side some adobe buttresses have been placed to
keep the loose earth out of the village street. This is all of mans
labor that is visible, except the work of the Indians in shaving away
the hill which constitutes this pyramid. As for the great city of
Cholula, it never had an existence."[IX-18] At a short distance from
the foot of the large pyramid, two smaller ones are mentioned by
several visitors; one of which is doubtless a portion of the chief
mound separated by the road that has been already mentioned. One
of them is described by Beaufoy as having perpendicular sides, and
built of adobes nine inches square and one inch thick; the second
was much smaller and had a corn-patch on its summit. Cuts of the
two small mounds are given by the same explorer. Bullock claims to
have found on the top of one of the detached masses a ditch and
wall forming a kind of figure-eight-formed enclosure one hundred
feet long, in which were many human bones. Evans has a theory
that the small mounds were formed of the material taken from the
larger one in shaping its terraces. Latrobe says that many ruined
mounds may be seen from the summit; in fact, that the whole
surface of the surrounding plain is broken by both natural and
artificial elevations. Ampère was led by his native guide, through a
misunderstanding, to a flat-topped terraced hill, still bearing traces
of a pavement, at a locality called Zapotecas.[IX-19]
The only miscellaneous Cholulan relics of which I find a mention, are
three described by Dupaix and sketched by Castañeda. They were, a
stone head, said to have originally been the top of a column; a
quadrangular block, with incised hieroglyphics on one of its faces;
and a mask of green jasper, reported to have been dug from the
pyramid.[IX-20]

REMAINS AT On the summit of the Sierra de Malinche, which


NATIVIDAD. forms the boundary between Puebla and
Tlascala, the existence of ruined walls and
pyramids, with fragments of stone images, is mentioned without
description.[IX-21] At San Pablo del Monte two kneeling naked
females in stone, modestly covering the breasts with the hands,
were sketched by Castañeda.[IX-22] Of an important group of
remains in the vicinity of Natividad, between Puebla de los Angeles
and Tlascala, a very unintelligible account has been written by
Cabrera, for the Mexican Geographical Society. The ruins seem to
cover a hill, different localities on the slopes of which are called
Mixco, Xochitecatl, Tenexotzin, Hueyxotzin, and Cacaxtlan. The
western slope has gigantic terraces, and among other relics five
vertical stones called huitzocteme, supposed to have been used for
sacrificial purposes. They are two varas high and three fourths of a
vara wide. On the northern slope a concavity of stone and mud is
mentioned, whose bottom is strewn with pottery and obsidian
weapons. At Cacaxtlan, the site of the principal fortress in the wars
between Tlascala and Mexico, are ditches and subterranean
passages running in all directions. The chief ditch extends from
north to south across the hill; it is about twenty-eight feet wide and
eleven or twelve feet deep, with embankments formed of the earth
thrown out. The subterranean passages are believed to penetrate
the heights of Cacaxtlan. One has an opening among the rocks on
the north, beginning at the cave of Ostotl; another begins on the
east at San Miguel del Milagro, having for an entrance a square hole
five or six yards deep, from the bottom of which it extends
horizontally in a semicircular course; the third opening is on the
south, and its top is supported by columns left in the volcanic stone;
and finally, the fourth subterranean passage sends out vapor when it
is about to rain. This is all I can glean from Cabrera's account—in
fact, rather more than I can fully understand.[IX-23] Dupaix found at
Natividad two wooden teponastles, or aboriginal musical
instruments, similar to the one found at Tlascala by the same
explorer and shown in the accompanying cut. The former were,
however, less elaborately carved; the latter was three feet long and
five inches in diameter, the cut showing a side and end view. Other
relics found by Dupaix in the city of Tlascala and vicinity, are the
following:—a lance-head, nine inches long, of green flint; a small
stone statue, nine or ten inches in height, representing a seated
female, whose head bears a strong resemblance to some of the
Palenque profiles; a mask of green agate a little smaller than the
natural size of the face, pronounced by Dupaix the finest specimen
of sculpture seen in America; an earthen vase called popocaxtli,
used in ceremonies in honor of the dead, found in connection with
some human bones; two mutilated human heads carved from a gray
stone; and a masked, bow-legged idol of stone, twenty-four inches
high, standing on a small pedestal, covering the breasts with the
hands.[IX-24]
Teponastle from Tlascala.

At Pueblo de los Reyes, northward from Tlascala,


ABORIGINAL
on the road to San Francisco, two aboriginal
BRIDGES.
bridges over a mountain stream were sketched
by Castañeda. One is eleven feet high and thirty-seven feet wide;
the other fifty-five feet high and thirty-three feet wide; each being
over a hundred feet in length. They are built of large irregular stones
in mortar. The conduits through which the stream passes are from
four to six feet wide and high, one of them having a flat top, while in
the other two large blocks meet and form an obtuse angle. On the
top of the bridges at the sides are parapets of brick four or five feet
high, pierced at intervals to allow water to run from the road; and at
each of the four corners stands a circular, symmetrical, ornamental
obelisk, or pillar, over forty feet high, of stone and mortar, covered
with burned bricks. It is quite probable that the brick-work of these
bridges, if not the whole structure, is to be referred to Spanish
rather than to aboriginal times. Sr Almaraz sketched at Xicotepec, in
the north, some fifty miles west of Papantla, a teponastle of iron-
wood, gracefully carved and brilliantly polished.[IX-25]
The famous wall that was found by Cortés, extending along the
frontier of Tlascala, has been spoken of in another part of this work.
Brasseur de Bourbourg tells us that many remains of this wall are
still visible, and some other authors vaguely speak to the same
effect; but as no modern traveler describes or locates these remains,
I think it altogether likely that the statements referred to may be
simply echoes of those made by the early writers, who represented
the ruins of the wall as visible in the years immediately following the
Conquest.[IX-26]

RELICS AT Passing westward into the state of Mexico, and


CUERNAVACA. beginning again in the south, I find a notice in a
Mexican government report, of ruins at Tejupilco,
in the south-west, about sixty miles westward of Cuernavaca. The
remains are noticed especially on the hill of Nanchititla, consisting of
buildings standing on regular streets yet traceable, and built of very
thin blocks, or slates, of stone without mortar. In the valley of San
Martin Luvianos, in the same region, a subterranean apartment with
polished sides of cement, discovered in 1841, contained quantities of
carbonized maize.[IX-27] At Zacualpan, midway between Cuernavaca
and Tejupilco, and some leagues further south, flint spear-heads,
stone masks, and other relics not specified are said by the same
authority to have been found in a cave.[IX-28] A peculiarity of the
aboriginal relics found by Dupaix at Cuernavaca and vicinity was that
all consisted of sculptured figures on the surface of large naturally
shaped boulders. The first was an immense lizard over eight feet
long and a foot and a half thick, carved in high relief on the top of a
rough block. Four small circular projections are seen on the side of
the rock below the animal. On the southern face of another isolated
boulder was sculptured in low relief the coat of arms shown in the
cut, which, in its principal features of a circle on parallel arrows or
lances, is very similar to others that have been mentioned.[IX-29] On
the flag that projects from the upper part of the circle, a Maltese
cross is seen, and the bird's head above is pronounced of course by
Dupaix to be that of an eagle.[IX-30] On the opposite, or northern,
side of the same boulder are sculptured the figures shown in the cut.
The left hand figure, thirteen inches high, may in connection with
the small circles be a record of a date—thirteen calli. M. Lenoir,
however, on account of the column shown within the building,
believes the whole may be an emblem of phallic worship, the column
being a phallus and the building its shrine or temple. The sculpture
on both sides of this rock is described as having been executed with
great care and clearness. Somewhat less than a league south of the
city is another isolated rock, said to have served as a boundary mark
to the ancient Quauhnahuac, 'place of the eagle,' of which the
modern name Cuernavaca is a corruption. On the face of this rock is
carved in rather high relief the figure represented in the cut, which,
in consideration of the aboriginal meaning of the name, and the
purpose served by the stone, may be regarded as an eagle. The
material is a fine gray stone, the bird is thirty-five inches high, and
the boulder, or its locality, is called by the natives Quauhtetl, 'stone
eagle.'[IX-31]

Coat of Arms—Cuernavaca.
Boulder-Sculptures at Cuernavaca.

Eagle of Cuernavaca.

The ruins of Xochicalco, doubtless the finest in


RUINS OF
Mexico, are about fifteen miles 13° west of south
XOCHICALCO.
from Cuernavaca, and about seventy-five miles
south-west from the city of Mexico. The first published description
was written by Alzate y Ramirez, who visited the locality in 1777, and
published his account with illustrative plates as a supplement to his
Literary Gazette in November, 1791.[IX-32] Humboldt made up his
account from that of Alzate; Dupaix and Castañeda included
Xochicalco in their first exploration; Nebel visited and sketched the
ruins in 1831; and finally an account, perhaps the most complete
extant, written from an exploration in 1835 by order of the Mexican
government, was published in the Revista Mexicana.[IX-33]

Xochicalco, the 'hill of flowers,'[IX-34] is a natural


RUINS OF
XOCHICALCO. elevation of conical form, with an oval base over
two miles in circumference, rising from the plain
to a height of nearly four hundred feet.[IX-35] Mr Latrobe claims to
have found traces of paved roads, of large stones tightly wedged
together, one of them eight feet wide, leading in straight lines
towards the hill from different directions. The account in the Revista
mentions only one such causeway running towards the east. A ditch,
more or less filled up and overgrown with shrubbery, is said to
extend entirely round the base of the hill, but its depth and width
are not stated; perhaps in the absence of more complete information
its existence should be considered doubtful.
Subterranean Galleries—Xochicalco.

Very near the foot of the northern slope are the entrances to two
tunnels or galleries, one of which terminates at a distance of eighty-
two feet; at least, it was obstructed and could not be explored
beyond that point. The second gallery, cut in the solid limestone of
the hill, about nine feet and a half wide and high, has several
branches running in different directions, some of them terminated by
fallen débris, others apparently walled up intentionally. The floors
are paved to the thickness of a foot and a half with brick-shaped
blocks of stone, the walls are also in many places supported by
masonry, and both pavement, walls, and ceiling are covered with
lime cement, which retains its polish and shows traces in some parts
of having had originally a coating of red ochre. The principal gallery,
after turning once at a right angle, terminates at a distance of
several hundred feet in a large apartment about eighty feet long, in
which two circular pillars are left in the living rock to support the
roof. The accompanying cut is Castañeda's ground plan of the
galleries and subterranean apartment, a being the entrance on the
north; b the termination of main gallery; c, k, the branch gallery; e
and d, obstructed passages; g, g, the room and f, f, the pillars. The
scale of the plan is about fifty feet to the inch, but the dimensions,
according to the scale, are doubtless inaccurate. According to the
plan the galleries are only a little over four feet wide; and the
apartment thirty-three by thirty-nine feet. Alzate's plan agrees with it
so far as it goes; the Revista gives no plan, and its description differs
in some respects, so far as the arrangement of the galleries is
concerned, from the cut.[IX-36] In the top of the room at the south-
east corner, at h, is a dome-like structure, a vertical section of which
is shown at j of the preceding cut, six feet in diameter and six feet
high, lined with stone hewn in curved blocks, with a round hole
about ten inches in diameter extending vertically upward from the
top. It has been generally believed that this passage leads up to the
pyramid on the top of the hill, to be described later; but it will be
seen that if the hill be two miles in circumference, or even half that
size, the galleries are not nearly long enough to reach the centre
under the pyramid. Nebel fancied that the hole in the cupola was so
situated that the rays of the sun twice a year would penetrate from
above and strike an altar in the subterranean hall. The natives report
other passages in the hill besides the one described, and believe that
one of them leads to Chapultepec, near the city of Mexico.
Passing now from the interior to the outer
THE HILL OF
FLOWERS.
surface of the 'hill of flowers,' we find it covered
from top to bottom with masonry. Five terraces,
paved with stone and mortar, and supported by perpendicular walls
of the same material, extend in oval form entirely round the whole
circumference of the hill, one above the other. Neither the width of
the paved platforms nor the height of the supporting walls has been
given by any explorer, but each terrace, with the corresponding
intermediate slope, constitutes something over seventy feet of the
height of the hill. The terrace platforms have sometimes been
described, without any authority, as a paved way leading round and
round the hill in a spiral course to the summit. Dupaix speaks of a
road about eight feet wide, which leads to the summit, but no other
explorer mentions any traces of the original means of ascent. Each
terrace wall, while forming in general terms an ellipse, does not
present a regular line, but is broken into various angles like the
bastions of a fortification. The pavements all slope slightly towards
the south-west, thus permitting the water to run off readily.
According to the plans of Alzate and Castañeda there are two
additional terraces where a spur projects from the hill at the north-
eastern base. Latrobe is the only authority on the intermediate
slopes between the terraces, which he says are occupied with
platforms, bastions, and stages one above another. It is evident from
all accounts that the whole surface of the hill, very likely shaped to
some extent artificially, was covered with stone work, and that
defense was one object aimed at by the builders. The Revista
represents the terrace platforms as additionally fortified by the
perpendicular supporting walls projecting upward above their level,
forming what may perhaps be termed a kind of parapet.
On the summit is a level platform measuring two hundred and
eighty-five by three hundred and twenty-eight feet.[IX-37] According
to Alzate, Humboldt, Dupaix, and other early authorities—except
Nebel, who is silent on the subject—this plaza is surrounded by a
wall. Dupaix says the wall is built of stones without mortar, is five
feet and a half high, and two feet and nine inches thick. Alzate
represents the wall as perpendicular only on the inner side, being in
fact a projection of the upper terrace slope, forming a kind of
parapet, and making the plaza a sunken area. Latrobe also speaks of
the plaza as a hollow square, and Alzate's representation is probably
a correct one; for the author of the account in the Revista says that
the wall described by previous visitors could not be found; and
moreover, that there was no room for it on the north between the
central pyramid and "one of the solid stone masses, or caballeros,
that surround the platform," the caballeros, which may perhaps in
this connection be translated 'parapets,' being doubtless the same
structures that the others describe as a wall.
In this plaza, cultivated in later years as a
PYRAMID OF
XOCHICALCO.
cornfield, there are several mounds and heaps of
stones not particularly described; and near the
centre is a pyramid, or rather the lower story of one, with
rectangular base, the sides of which, exactly or very nearly facing
the cardinal points, measure sixty-five feet from east to west, and
fifty-eight feet from north to south. The lower story, which in some
parts is still standing to its full height, is divided into what may be
termed plinth, frieze, and cornice, and is about sixteen feet high.[IX-
38]

Pyramid of Xochicalco.

In the centre of one of the façades is an open space, something over


twenty feet wide, bounded by solid balustrades, and probably
occupied originally by a stairway, although it is said that no traces of
steps have been found among the débris. The cut, from Nebel,
shows the front of the pyramid on one side of the opening, being
the eastern portion of the northern front, according to Nebel, who
locates the stairway on the north, or the northern part of the
western front, according to the Revista, which speaks of the opening
as being on the west.
The pyramid, or at least its facing, is built of large blocks of granite
or porphyry,[IX-39] a kind of stone not found within a distance of
many leagues. The blocks are of different sizes, the largest being
about eleven feet long and three feet high, and few being less than
five feet in length. They are laid without mortar, and so nicely is the
work done that the joints are scarcely perceptible. The cut shows
one of the façades, probably the northern, from Castañeda's
drawing, which corresponds almost exactly to that given by Alzate.
So far as the details of the sculpture are concerned it is probably not
very trustworthy. The preceding cut, from Nebel, is perhaps the only
reliable drawing in this respect that has been published. The whole
exterior surface seems to have been covered with sculptured figures
in low relief, apparently executed after the stones were put in place,
since one figure extends, with the greatest exactitude at the joints,
over several blocks of stone.[IX-40]

Pyramid of Xochicalco.

I translate from the Revista the following remarks about the


sculptured figures: "At each angle, and on each side, is seen a
colossal dragon's head, from whose great mouth, armed with
enormous teeth, projects a forked tongue; but in some the tongue is
horizontal, while in others it falls vertically; in the first it points
towards a sign which is believed to be that of water, and in the
others towards different signs or emblems.... Some have pretended
to see in these dragons images of crocodiles; but nothing certain can
be known of these fantastic figures which have no model in
nature.... On the two sides still standing there are two figures of
men larger than the natural size, seated cross-legged in the eastern
fashion, wearing necklaces of enormous pearls, rich ornaments, and
a head-dress out of all proportion, with long flowing plumes. In one
hand they hold a kind of sceptre, and the other is placed on the
breast; a hieroglyphic of great size, placed in the middle of each
side, separates the two figures, whose heads are turned, on the east
side, one north and the other south, while on the north side both
face the west. The frieze which surrounds this story presents a
series of small human figures, also seated in the eastern manner,
with the right hand crossed on the breast, and the left resting on a
curved sword, whose hilt reminds us of ancient swords; a thing the
more worthy of attention since no people descended from the
Toltecs or Aztecs has made use of this kind of arms. The head-dress
of these small figures, which closely resemble those mentioned
before, is always disproportionately large, and this circumstance,
which is found in all the Egyptian mythologic fables, is considered in
the latter an emblem of power or divinity. With the human figures
are seen various signs, some of which seem allegorical and others
chronologic, so far as may be judged from their conformity with
those employed in the Aztec paintings.... Another sign, apparently of
a different nature, is often repeated among the figures; it is a
dragon's mouth, open and armed with teeth, as in the large reliefs,
from which projects instead of a tongue a disk divided by a cross....
It has also been thought (Alzate) that dances are represented on the
frieze of Xochicalco, but its perfect preservation makes such an error
inexcusable, and figures seated with legs crossed and hands on a
sword, exclude any idea of sacred or warlike dances, and suggest
only mythologic or historical scenes. Over the frieze was a cornice
adorned with very delicate designs in the form of oalmetas or
meandres in the Greek style." The cut shows one of the bas-reliefs
on a larger scale than in the preceding illustrations. There is, as
Nebel observes, a certain likeness between these sculptured designs
and the stucco reliefs of Palenque, although in the architectural
features of the monument, and of the base on which it rests, there
seems to be no analogy whatever with any of the southern ruins.

Bas-Relief from Xochicalco.

On the summit of this lower structure a few sculptured foundation


stones of a second story were found yet in place, the walls being
two feet and three inches from the edge of the lower, except on the
west, where the space is four feet and a half. According to the report
of the inhabitants of the vicinity, the structure had originally five
receding stories, similar to the first in outward appearance, which
were all standing as late as 1755, making the whole edifice probably
about sixty-five feet high. It is said to have terminated in a platform,
on the eastern side of which stood a large block, forming a kind of
throne, covered with hieroglyphic sculpture. The proprietors of
neighboring sugar-works were the authors of the monument's
destruction, the stone being of a nature suitable for their furnaces,
and none other being obtainable except at a great distance. Alzate
puts on record the name of one Estrada as the inaugurator of this
disgraceful work of devastation.[IX-41] Several restorations of the
pyramid of Xochicalco have been attempted on paper, that by the
artist Nebel being probably the only one that bears any likeness to
the original; and even his sketch, so far as the sculptured designs
are concerned, must be regarded as extremely conjectural, having
as a foundation only a few scattered blocks and the reports of the
'oldest inhabitant.' At the Paris international exhibition in 1867 a
structure was built and exhibited in the Champs de Mars, purporting
to be a fac-simile of this monument; but judging from a cut
published in a London paper, it might with equal propriety have been
exhibited as a model of any other ruin in the new or old world.[IX-42]
The second story seems to have had interior apartments, with three
doorways at the head of the grand stairway. On the summit of the
lower story, according to the Revista, is a pit, perhaps a covered
apartment originally, measuring twenty-two feet square, and nearly
filled with fragments of stone, some of them sculptured, which were
not removed. It is of course possible that there exists some means
of communication between this apartment and the subterranean
galleries of the hill below.
East of the hill of Xochicalco, on the road to Miacatlan, an immense
stone was said to have been found serving as a kind of cover to a
hole, perhaps the entrance to a subterranean gallery, on the face of
which was sculptured an eagle tearing a prostrate native
Prometheus. It was broken up and most of the pieces carried away,
but Alzate saw one fragment containing a part of the sculptured
thigh, from which perhaps with the aid of his imagination and his
knowledge of Grecian mythology the good padre prepared a drawing
of the whole, which he published. Later visitors have not even seen
a fragment of so wonderful a relic. Mr Tylor speaks of a small paved
oval space somewhere in connection with the ruin, in which he
found fragments of a clay idol. There are no springs of water on or
near the hill.
The Revista says, "adjoining this hill is another higher one, also
covered with terraces of stone-work in form of steps. A causeway of
large marble flags led to the top, where there are still some
excavations and among them a mound of large size. Nothing further
in the way of monuments is to be seen on the lower (part of the?)
hill except a granite block, which may be the great square stone
mentioned by Alzate, which served to close the entrance to a
subterranean gallery, situated east of the principal monument."
There are also some traces of one terrace indicated on Castañeda's
view of the larger hill. On the sculptured façades of the pyramid, all
have found traces of color in sheltered places, and have concluded
that the whole surface was originally painted red, except the author
of the account in the Revista, who thinks that the groundwork of the
reliefs only was covered with a colored varnish, as was the usage in
Egypt. Löwenstern claims to have found in the vicinity of Xochicalco
the foundation of many aboriginal dwellings.
A slight resemblance has been noted in some of the sculptured
human figures, seated cross-legged, to the Maya sculptures and
stucco reliefs of Central America; a few figures, like that of the
rabbit, may present some analogies to Aztec sculptures, many
specimens of which will be shown in the present chapter; the very
fact of its being a pyramid in several stories, gives to Xochicalco a
general likeness to all the more important American ruins; the
terraces on the hill-slopes have their counterparts at Quiotepec and
elsewhere; the absence of mortar between the façade-stones is a
feature also of Mitla; still as a whole the monument of Xochicalco
stands alone; both in architecture and sculpture it presents strong
contrasts with Copan, Uxmal, Palenque, Mitla, Cholula, Teotihuacan,
or the many pyramids of Vera Cruz. There is no definite tradition
referring the origin of this monument to any particular pre-Aztec
period, save the universal modern tradition among the natives
referring everything wonderful to the Toltecs. It is not, moreover,
improbable that the pyramid was built by a Nahua people during the
Aztec period; for it must be remembered first that all the grand
temples in Anáhuac—the Aztec territory proper—have disappeared
since the Conquest, so that a comparison of such buildings with that
of Xochicalco is impossible; and second, that the Aztecs were
superior to the nations immediately surrounding them in war rather
than art, so that it would be by no means surprising to find a
grander temple in Cuernavaca than in the valley of Mexico. The
Aztec sculpture on such monuments as have been found in the city
of Mexico if different from, is not inferior to that at Xochicalco, and
there is no reason whatever to doubt the ability of the Aztecs to
build such a pyramid. Still there remains of course the possibility of a
pre-Aztec antiquity for the building on the hill of flowers, and of
Maya influence exerted upon its builders.[IX-43]

REMAINS IN THE
SOUTH-EAST.

Sculptured stone—Casasano.

In the south-eastern part of the state from Yahualica northward to


Mecamecan, relics have been discovered, mostly by Dupaix, in
several localities. At Yahualica, near Huautla, there are tombs, with
stone images, human remains, pottery, and metates, also some
metallic relics not described.[IX-44] At Xonacatepec was seen a mask
of about the natural size, carved very neatly from a whitish
translucent stone.[IX-45] At the sugar plantation of Casasano, in the
same region, a somewhat remarkable relic was a stone chest, of
rectangular base, larger at the bottom than at the top, with a cover
fitting like that of a modern chest. It was cut from a grayish stone,
and when found by laborers engaged in digging a ditch, is said to
have been filled with stone ornaments. At the same place was seen
a circular stone, three feet in diameter and nine inches thick,
sculptured in geometric figures on one side, as shown in the
preceding cut.[IX-46]
Another similar stone of the same thickness, and about three feet
and a half in diameter, was built into a modern wall at Ozumba.
These geometrically carved circular blocks are of not infrequent
occurrence on the Mexican plateaux; of their use nothing is known,
but they seem to bear a vague resemblance to the Aztec calendar
and sacrificial stones to be described later. Another class of circular
blocks, from two to three feet in diameter, with curves and various
ornamental figures sculptured on one face, are also of frequent
occurrence. Several of this class will be mentioned and illustrated in
connection with the relics of Xochimilco. Two of them were seen by
Dupaix at Chimalhuacan Tlachialco, near Ozumba, together with two
small idols of stone. At Ahuehuepa, in the same region, was a statue
which had lost the head and the legs below the knees; a
hieroglyphic device is seen on the breast, and a small cord passes
round the waist, and is tied in a bow-knot in front. Two fragments of
head-dresses carved in red stone were found at the same place. A
few miles east of the village of Mecamecan is an isolated rock of
gray granite, artificially formed into pyramidal shape as shown in the
cut. It is about twelve feet high and fifty-five feet in circumference,
having rudely cut steps, which lead up the eastern slope. Dupaix
conjectures that this monument was intended for some astronomic
use, and that the man sculptured on the side is engaged in making
astronomical observations, the results of which are expressed by the
other figures on the rock. The only possible foundation for the
opinion is the resemblance of some of the signs to those by which
the Aztecs expressed dates.[IX-47]
Pyramidal stone—Mecamecan.

Entering now the valley of Mexico, we find many


REMAINS IN localities on the banks, and islands of Lake
ANÁHUAC. Chalco where relics of the ancient inhabitants
have been brought to light. At Xochimilco on the
REMAINS AN western shore of the lake, Dupaix mentions the
XOCHIMILCO. following:—1st. A stone block with regular sides,
on one of which about three feet square are
sculptured two concentric circles, as large as the space permits, with
smaller circles outside of the larger, at each corner of the block. 2d.
A crouching monster of stone thirty inches high, which apparently
served originally for a fountain or aqueduct, the water flowing
through the mouth. 3d. A semi-spherical pedestal of limestone,
broken in two pieces, three feet high, and decorated on the curved
surface with oval figures radiating from the centre. 4th. A lizard
thirty inches long, sculptured on a block which is built into a modern
wall. 5th. A coat of arms, also on a block in a wall, consisting of a
circle on parallel lances like some already described. Within the circle
is a very perfect Maltese cross, hanging from the lower part is a fan-
like plume, and elsewhere on the smooth faces of the stone are nine
very peculiar knots or tassels. 6th. A kind of flat-fish three feet eight
inches long, carved from a bluish gray stone. 7th. A coiled serpent in
red porphyry, a foot and a half in diameter, and nine feet long if
uncoiled. This relic is shown in the cut. 8th. Two death's heads in
stone. 9th. A rabbit in low relief on a fragment of stone. 10th. An
animal in red stone on a cubic pedestal of the same material. 11th.
A stone image of a seated female. 12th. An idol with a man's head
and woman's breasts. 13th. Ten sculptured blocks, the faces of
which are shown in the following cut, and which would seem to have
served only for decorative purposes. Most of them have rough
backs, evidently having been taken from ancient walls; and many of
these and other similar blocks found in this region had tenons like
that shown in fig. 9 of the cut. Fig. 7 shows one of the several
death's heads found at Xochimilco.

Coiled Serpent—Xochimilco.
Sculptured Stones—Xochimilco.

Sculptured Vase—Tlahuac.

At Tlahuac, or Cuitlahuac, were seen two circular stones something


over three feet in diameter and half as thick, of black porous
volcanic material. Each had a circular hole in the centre, rude incised
figures on the faces, and a tenon at one point of the circumference.
They strongly remind me of the rings in the walls of the so-called
gymnasium at Chichen in Yucatan. Another relic was a cylindrical
stone of a hard gray material, of the same dimensions as the
preceding, but without a supporting tenon. The circular faces were
plain, but the sides, or rim, were decorated with circles, bands, and
points symmetrically arranged and sculptured in low relief. And
finally there was found at Tlahuac the very beautiful vase of hard
iron-gray stone shown in the cut. It is eight feet four inches in
circumference on the outside, one foot nine inches in diameter on
the inside, and elaborately sculptured in low relief on both the
exterior and interior surface. In Kingsborough's edition of Dupaix's
work it is stated that the two causeways which led to the town
across the waters of Lake Chalco are still in good preservation, five
or six yards wide and of varying height, according to the depth of
the water. In the report of the Ministro de Fomento in 1854 there is
also a mention of a dike built to keep the waters of the lake from
Mexico. Another dike, serving also as a causeway at Tulyahualco is
mentioned in the same report.
At Xico, on an island in Lake Chalco, there are some traces of an
aboriginal city, in the shape of foundation walls of masonry, stone
terraces, and what is very important if authentic, well-burned bricks
of different forms and dimensions. In the Mexican government
report referred to, the foundations of a palace are alluded to.
At Misquique, on another of the lake islands Dupaix found the
following objects left by the antiguos:—1st. A sculptured monster's
head, with a tenon for insertion in a wall. 2d. A large granite vase,
circular in form, four feet and a half in diameter, three feet and a
half high, sculptured on the upper rim, painted on the inside, and
polished on the outer surface. It rests on a cylindrical base, smaller
than the vase itself, and is used in modern times as a baptismal font.
3d. A mill-stone shaped block, with a tenon, very similar to those
found at Tlahuac, except that the sculptures on the face are
evidently in low relief in this case. 4th. An animal called by Dupaix a
coyote, sculptured on the face of a block. 5th. A cylindrical stone
twenty-one inches in diameter and twenty-eight in height, round the
circumference of which is sculptured, or apparently merely incised, a
serpent. 6th. A square block with concentric circles and other
figures, similar to those at Xochimilco. 7th. Another block with a
spiral figure. 8th. A very finely formed head of gray veined stone,
furnished with a tenon at the back of the neck. 9th. Three small and
rudely formed images, one of green jasper and two of a red stone.

Animal in Stone—Tlalmanalco.

At Tlalmanalco were four small idols in human


TLALMANALCO AND
CULHUACAN.
form, three of which were built into a modern
wall; two heads, one of which is of chalchiuite;
three of the ornamental blocks, one bearing clearly defined cross-
bones; and the nondescript animal in gray stone shown in the cut.
Also at Tlalmanalco, in the official report already several times cited,
mention is made of three fallen pyramids, one of which was
penetrated by a gallery, supposed to have been intended for burial
purposes.

Terra-Cotta Idol—Culhuacan.
Culhuacan, on the north-eastern bank of the same lake, is a small
village which retains the name of the city which once occupied the
site, famous in the annals of Toltec times. Veytia tells us that in his
time some vestiges of the ancient capital were still visible; and
Gondra describes a clay idol found at Culhuacan, and shown in the
cut, as an image of Quetzalcoatl, giving, however, no very clear
reasons for his belief. This relic is fourteen inches high, thirteen
inches wide, and is preserved in the Mexican Museum.[IX-48]
The relics discovered in Anáhuac at points westward from the lakes,
I shall describe without specifying in my text the exact locality of
each place referred to. At Chapultepec there is a tradition that
statues representing Montezuma and Axayacatl were carved in the
living rock of the cliff; and these rock portraits are said to have
remained many years after the Conquest, having been seen by the
distinguished Mexican scientist Leon y Gama. Brasseur de Bourbourg
even claims to have seen traces of them, but this may perhaps be
doubted. One was destroyed at the beginning of the eighteenth
century by order of the over-religious authorities; but the other
remained in perfect preservation until the year 1753, when it also
fell a victim to anti-pagan barbarism. The immense cypresses or
ahuehuetes that still stand at the foot of Chapultepec, 'hill of the
grasshopper,' are said to have been large and flourishing trees
before the coming of the Spaniards.[IX-49]
A few miles from the celebrated church of
HILL OF
OTONCAPOLCO.
Nuestra Señora de los Remedios, is a terraced
stone-faced hill, similar perhaps in its original
condition to Xochicalco, except that the terraces are more numerous
and only three or four feet high. Although, only a short distance
from the capital in an easily accessible locality, only two writers have
mentioned its existence—Alzate y Ramirez in 1792 and Löwenstern
in 1838. The former calls the hill Otoncapolco, and his article in the
Gaceta de Literatura is mainly devoted to proving that this was the
point where Cortés fortified himself after the 'noche triste,' instead of
the hill on which the church of Remedios stands, as others in
Alzate's time believed. The author, who visited the place with an
artist, says, "I saw ruins, and hewn stones of great magnitude, all of
which proves to the eye that this was a fortification, or as the
historians say, a temple, because they thought that everything made
by the Indians had some connection with idolatry; it is sure that in
the place where the celebrated sanctuary stands, there is not found
the slightest vestige of fortress or temple, while on the contrary, all
this is observed at Otoncapolco." This with the remark that this
monument, although not comparable to Xochicalco, yet merits
examination, is all the information Padre Alzate gives us; and
Löwenstern adds but little to our knowledge of the monument. He
found débris of sculptured stone, obsidian, vases, and pottery; also
the ruins of a castle two-thirds up the slope, in connection with
which was found a flat stone over six feet long, bearing a sculptured
five-branched cross—a kind of coat of arms. The hill is from two
hundred and sixty to three hundred and twenty-five feet high, has a
square summit platform, and the whole surface of its slopes was
covered with stone-work, now much displaced, in the shape of
steps, or terraces, between three and four feet high. At one point
the explorer found, as he believed, the entrance to a subterranean
passage, into which he did not enter but inserted a pole about nine
feet.[IX-50]
At Tacuba, the ancient Tlacopan, Bradford mentions the "ruins of an
ancient pyramid, constructed with layers of unburnt brick," and
Löwenstern speaks of broken pottery and fragments of obsidian. The
latter author also claims to have seen near the church of Guadalupe
the foundations of many small dwellings which constituted an
aboriginal city.[IX-51] At Malinalco, near Toluca, two musical
instruments, tlamalhuilili, are mentioned. They were carved from
hard wood and had skin stretched across one end, being three feet
long and eighteen inches in diameter.[IX-52] Mr Foster gives a cut of
a tripod vase in the Chicago Academy of Sciences, which was dug up
near San José. "It is very symmetrically moulded, and is ornamented
by a series of chevrons or small triangles. This chevron mode of
ornamentation appears to have been widely prevalent."[IX-53]

CITY OF MEXICO. In describing the relics which have been


discovered from time to time in the city of Mexico,
the ancient Aztec capital, I shall make no mention for the present of
such objects, preserved in public and private antiquarian collections
in that city, as have been brought from other parts of the state or
republic. When the locality is known where any one of this class of
relics was found I shall describe it when treating of antiquities in that
locality. The many relics whose origin is unknown will be alluded to
at the end of this chapter. Since all who have visited Mexico or
written books about that country, almost without exception, have
had something to say of antiquities and of the collections in the
National Museum, as well as of the relics belonging strictly to the
city, I shall economize space and avoid a useless repetition by
deferring a list of such authorities to my account of the
miscellaneous relics of the Mexican Republic at the end of the
chapter, referring for my present purpose only to the more important
authorities, or such as contain original information or illustrations.
No architectural monuments whatever remain within the city limits.
The grand palaces of the Aztec monarchs, the palatial residences of
the nobility, the abodes of wealth and fashion, like the humbler
dwellings of the masses, have utterly disappeared; monuments
reared in honor of the gods have not outlasted the structures
devoted to trade; the lofty teocalli of the blood-thirsty Huitzilopochtli,
like the shrines of lesser and gentler deities, has left no trace.
Movable relics in the shape of idols and sculptured stones are not
numerous, although some of them are very important. No
systematic search for such monuments has ever been made, and
those that have been brought to light were accidentally discovered.
Some sculptured blocks of the greatest antiquarian value have been
actually seen in making excavations for modern improvements, and
have been allowed to remain undisturbed under the pavements and
public squares of a great city! There can be no doubt that thousands
of interesting monuments are buried beneath the town. The
treasures of the Plaza Mayor will perhaps be some day brought out
of their retirement to tell their story of aboriginal times, but
hundreds of Aztec divinities in stone will sleep on till doomsday. It is
unfortunate that these gods of other days cannot regain for a time
the power they used to wield, turn at least once in their graves, and
shake the drowsy populace above into a realization of the fact that
they live in the nineteenth century.
The three principal monuments of Mexico Tenochtitlan are the
Calendar-Stone, the so-called Sacrificial Stone, and the idol called
Teoyaomiqui. They were all dug up in the Plaza Mayor where the
great teocalli is supposed to have stood, and where they were
doubtless thrown down and buried from the sight of the natives at
the time of the Conquest. In the years 1790 to 1792 the plaza was
leveled and paved by order of the government, and in the
excavations for this purpose and for drainage the three monuments
were discovered, the Calendar-Stone and the idol very near the
surface, and the third relic at a depth of twenty-five or thirty feet.
The Calendar-Stone was a rectangular parallelopipedon of porphyry,
thirteen feet one inch and a half square, three feet three inches and
a half thick, and weighing in its present mutilated state twenty-four
tons. The sculptured portion on one side is enclosed in a circle
eleven feet one and four-fifths inches in diameter. These are the
dimensions given by Humboldt, who personally examined the stone,
and agree almost exactly with those given by Leon y Gama, who
examined and made drawings of the monument immediately after its
discovery. Gama pronounced the material to be limestone, which
provoked a sharp controversy between him and Padre Alzate, the
latter calling the material, which he tested by means of acids, a
volcanic rock. Humboldt's opinion is of course decisive in such a
matter. The centre of the circle does not exactly correspond with
that of the square, and Gama concludes from this circumstance that
the stone had a companion block which might be found near the
place where this was found.[IX-54]

THE CALENDAR-
STONE.

Aztec Calendar-Stone.

The stone has been for many years built into the wall of the
cathedral at the base, where it is exposed to the view of all passers-
by, and to the action of the elements. While lying uncovered in the
plaza it was considerably mutilated by the natives, who took the
opportunity of manifesting their horror of the ancient gods, by
pelting with stones this relic of their paganism. Parts of the stone
were also broken off when it was thrown down and buried by the
conquistadores. Fortunately the sculptured portions have been but
slightly injured, and are shown in the cut. The plates published by
Gama, Humboldt, Nebel, Mayer, and others, are all tolerably
accurate; except that they were drawn to represent the stone
correctly on the plate or block, and of course reversed in printing.
The origin of this error is probably to be found in the fact that nearly
all have copied Gama's plate. In my cut the error is corrected and
the sculptured figures agree exactly with Charnay's photograph.[IX-
55] These figures are the symbols of the Aztec calendar, many of
which are well understood, while others are of unknown or disputed
signification. The calendar has been sufficiently explained in a
preceding volume, and I shall not enter upon its elucidation here.
The sculpture is in low relief, very accurately worked, and the circle
which encloses it projects, according to Mayer, seven inches and a
half, according to Gama and Nebel about three inches, and the rim
of the circle is also adorned with sculptures not shown in the cut.
Respecting the excellence of the sculpture Humboldt says: "the
concentric circles, the divisions, and the subdivisions without number
are traced with mathematical exactitude; the more we examine the
details of this sculpture, the more we discover this taste for
repetitions of the same forms, this spirit of order, this sentiment of
symmetry, which, among half-civilized peoples, take the place of the
sentiment of the beautiful."
No stone like that from which the Calendar-Stone is hewn, is found
within a radius of twenty-five or thirty miles of Mexico, and this may
be regarded as the largest block which the natives are known to
have moved over a long distance. Prescott tells us that the stone
was brought from the mountains beyond Lake Chalco, and was
dropped into the water while being transported across one of the
causeways. There is no reason to attribute this monument to any
nation preceding the Aztecs, although the calendar itself was the
invention of an older people. Wax models of this and other relics,
described by Mr Tylor as very inaccurate, are sold in Mexico; and a
plaster cast, taken by Mr Bullock in 1823, was exhibited in London.
[IX-56]

Sacrificial Stone—Mexico.

The Sacrificial Stone, so called, is a cylindrical


THE SACRIFICIAL
STONE.
block of porphyry, nine feet and ten inches in
diameter, three feet seven and one fourth inches
thick. This also was dug from the Plaza Mayor, was carried to the
courtyard of the University, where it has lain ever since, much of the
time half covered in the ground, and where different visitors have
examined it. The cut, which I have copied from Col. Mayer's
drawing, shows the sculpture which covers one side of the stone,
the other side being plain. The name of Sacrificial Stone, by which it
is generally known, probably originated from the canal which leads
from the centre to the edge, and which was imagined to have
carried off the blood of sacrifices; but the reader will notice at once
that this stone bears not the slightest resemblance to the altars on
which the priests cut out the hearts of their human victims, as
described in a preceding volume. Some authors, among whom is
Humboldt, believe this to be the temalacatl, or gladiatorial stone, on
which captives were doomed to fight against great odds until
overcome and put to death. The bas-relief sculptures, the central
concavity, the canal, and the absence of any means of securing the
foot of the captive, are very strong arguments against this use of the
cylinder. A smooth surface would certainly be desirable for so
desperate a conflict, and the sculptured figures on the rim, or
circumference, soon to be noticed, show that the plain side of the
stone was not in its original position uppermost. Gama, the first to
write about the monument, pointed out very clearly the objections to
the prevailing ideas of its aboriginal purpose. He claimed that the
stone was, like the one already described, a calendar-stone, on
which was inscribed the system of feast-days. The strongest
objection to this theory was the existence of the central concavity
and canal, which, however, Gama considers not to have belonged to
the monument at all, but to have been added by the ruder hands of
those who wished to blot out the face of the sun which originally
occupied the centre. Latrobe also says, "I have but little hesitation in
asserting that the groove in the upper surface formed no part of the
original design;" but Col. Mayer, who has carefully examined this
relic, tells me that the canal presents no signs whatever of being
more recent than the other carving, and it must be admitted that the
Spaniards would hardly have adopted this method of mutilation.
Tylor suggests that this was a sacrificial altar, but used for offerings
of animals. Fossey speaks of it as a 'triumphal stone.' But in alluding
to these theories I am departing somewhat from my purpose, which
is to give all the information extant respecting each relic as it exists.
Sculpture on the Sacrificial Stone.

The whole circumference of the stone is covered with sculptured


figures, consisting of fifteen groups. Each group contains two human
figures, apparently warriors or kings, victor and vanquished, differing
but little in position or insignia in the different groups, but
accompanied by hieroglyphic signs, which may express their names
or those of their nations. Two groups as sketched by Nebel are
shown in the cut. According to Gama these sculptured figures
represent by the thirty dancers the festivities celebrated twice each
year on the occasion of the sun passing the zenith; and also
commemorate, since the festivals were in honor of the Sun and of
Huitzilopochtli, the battles and victories of the Aztecs, the
hieroglyphics being the names of conquered provinces, and most of
them legible.[IX-57]
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like