Você está na página 1de 5

Não há como negar: Rx é um dos tópicos mais quentes no desenvolvimento de

aplicativos móveis atualmente!


Se você visitar conferências internacionais, ou mesmo encontros locais, pode parecer
que todo mundo está falando sobre observáveis, efeitos colaterais e agendadores
(gulp).
E não é à toa - Rx é um padrão multiplataforma, portanto, não importa se é uma
conferência de desenvolvimento web, um encontro Android local ou um workshop
Swift, você pode acabar participando de uma discussão multiplataforma sobre Rx.
A biblioteca RxSwift (parte da família maior de portas Rx em plataformas e linguagens)
permite que você use sua linguagem de programação Swift favorita de uma maneira
completamente nova. O código assíncrono um pouco difícil de manusear no Swift se
torna muito mais fácil e muito mais sensato de escrever com o RxSwift.
Para criar aplicativos responsivos e robustos, você precisa lidar com várias tarefas
simultâneas, como reproduzir áudio, manipular a entrada da interface do usuário,
fazer chamadas de rede e muito mais. Às vezes, passar dados de um processo para
outro ou até mesmo observar que as tarefas acontecem na sequência correta uma
após a outra de forma assíncrona pode causar muitos problemas ao desenvolvedor.
"Se você já usou uma API baseada em retorno de chamada assíncrono, provavelmente
já lidou com a manipulação de dados de resposta ad-hoc em toda a sua base de código
e provavelmente decidiu que não havia como testar tudo isso... deixe-me dizer-lhe - há
uma maneira melhor, e chama-se Rx!"
— Krunoslav Zaher, criador do RxSwift
16. raywenderlich. com
RxSwift - Programação reativa com Swift Introdução
Neste livro, você aprenderá como o RxSwift resolve os problemas relacionados à
programação assíncrona e domina várias técnicas reativas, desde observar sequências
de dados simples, combinar e transformar fluxos de valor assíncronos, projetar a
arquitetura e criar aplicativos de qualidade de produção.
Ao final deste livro, você terá trabalhado no conteúdo do capítulo e terá experiência
prática para resolver os desafios no final dos capítulos - e estará no caminho certo para
criar seu próprio Rx Padrões e Soluções!
O que você precisa
Para acompanhar os tutoriais deste livro, você precisará do seguinte:
• Um Mac executando a versão pontual mais recente do OS X High Sierra ou posterior:
você precisará disso para poder instalar a versão mais recente do Xcode.
• Xcode 10 ou posterior: Xcode é a principal ferramenta de desenvolvimento para iOS.
Você pode baixar a versão mais recente do Xcode gratuitamente na Mac App Store
aqui: https://itunes.apple.com/app/xcode/id497799835?mt=1
• Conhecimento de nível intermediário em desenvolvimento Swift e iOS. Este livro
trata especificamente do aprendizado do RxSwift; Para entender o restante do código
do projeto e como os projetos de demonstração que o acompanham funcionam, você
precisará de pelo menos um entendimento intermediário de Swift e UIKit.
Se você quiser experimentar em um dispositivo iOS físico, precisará de uma conta de
desenvolvedor da Apple, que pode ser obtida gratuitamente. No entanto, todos os
projetos de amostra neste livro funcionarão bem no iOS Simulator empacotado com o
Xcode, portanto, a conta de desenvolvedor paga é totalmente opcional.
17. raywenderlich. com
RxSwift - Programação Reativa com Swift Introdução A quem se destina este livro
Este livro é para desenvolvedores iOS que já se sentem confortáveis com iOS e Swift e
querem se aprofundar no desenvolvimento com RxSwift.
Se você é um iniciante completo no iOS, sugerimos que você leia primeiro a última
edição do iOS Apprentice. Isso lhe dará uma base sólida para criar aplicativos iOS com
Swift desde o início, mas talvez você ainda precise aprender mais sobre o
desenvolvimento iOS de nível intermediário antes de poder trabalhar em todos os
capítulos deste livro.
Se você conhece o básico do desenvolvimento iOS, mas é novo no Swift, sugerimos
que você leia primeiro o Swift Apprentice, que aborda os recursos do Swift usando
playgrounds para ensinar o idioma.
Você pode encontrar esses dois livros em nossa loja online:
http://store.wonderful.com
Como usar este livro
Geralmente, cada capítulo deste livro inclui um projeto inicial e abrange um pequeno
número de técnicas de programação em detalhes. Alguns dos capítulos tratam
principalmente de teoria, então você pode experimentar partes isoladas de código,
enquanto aprende o processo em um playground Swift.
Outros capítulos fornecem a você um projeto inicial que inclui alguma lógica não-Rx
interna e conduz você através da qualificação Rx do projeto, adicionando código em
locais-chave. No processo, você verá a diferença que o RxSwift faz no código do
projeto e como abordar diferentes problemas comuns.
Sugerimos que você trabalhe os capítulos em ordem, uma vez que os conceitos são
construídos um sobre o outro. Lembre-se de que você tirará o máximo proveito do
livro se seguir os tutoriais e realizar os desafios práticos.
Para desenvolvedores avançados, ainda há valor nos primeiros capítulos, pois eles
cobrem o básico. No entanto, se você estiver confortável com esses conceitos, sinta-se
à vontade para pular para os tópicos que mais lhe interessam.
18. raywenderlich. com

RxSwift - Programação reativa com Swift Introdução W

Section I: Getting Started with


RxSwift
In this part of the book, you’re going to learn about the basics of RxSwift. You are
going to have a look at what kinds of asynchronous programming problems RxSwift
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 RxSwift!


Chapter 2: Observables
Chapter 3: Subjects
Chapter 4: Observables & Subjects in Practice

raywenderlich.com 22

1
RxSwift!
Chapter 1: Hello,

By Marin Todorov

This book aims to introduce you, the reader, to the RxSwift library and to writing
reactive iOS apps with Swift.

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

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

RxSwift 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 23

RxSwift - Reactive Programming with Swift Chapter 1: Hello, RxSwift!

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

You’ll start with the basic features of RxSwift, 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 RxSwift 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 RxSwift is though, have we? Let’s 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.

As an iOS app developer, this should be much more clear and tell you more about what
RxSwift 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 RxSwift helps you write
asynchronous code. And you know that developing good, deterministic, asynchronous
code is hard, so any help is quite welcome!

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 iOS app, at any moment, might be doing any of the following things and more:

 Reacting to button taps


 Animating the keyboard as a text field loses focus
 Downloading a large photo from the Internet
 Saving bits of data to disk
 Playing audio

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


code to react to new data and process it in a sequential, isolated manner.

raywenderlich.com 24

RxSwift - Reactive Programming with Swift Chapter 1: Hello, RxSwift!

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. iOS offers you
various kinds of 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 argue about
which piece of code updates the data first, or which code read the latest value.

Cocoa and UIKit asynchronous APIs


Apple provides lots of APIs in the iOS SDK that help you write asynchronous code.
You’ve used these in your projects and probably haven’t given them a second thought
because they are so fundamental to writing mobile apps.

You’ve probably used most of the following:

• NotificationCenter: To execute a piece of code any time an event of interest happens,


such as the user changing the orientation of the device or the software keyboard
showing or hiding on the screen.

• The delegate pattern: Lets you define an object that acts on behalf, or in coordination
with, another object. For example, in your app delegate, you define what should happen
when a new remote notification arrives, but you have no idea when this piece of code
will be executed or how many times it will execute.

Você também pode gostar