Implementing state with scan in RxSwift

Intro Common misconception is that you cannot have state with Rx. Well you can - and there’s a special operator that helps you to: scan. If you’ve ever used reduce in Swift - scan is a very similar operator but reduce goes over the complete sequence and gives you the final value of the accumulator while scan emits each intermediate value as well. If you haven’t used reduce - no worries you’ll get to understand scan from the examples below.

Split laps timer with RxSwift and RxCocoa

I was browsing through RxMarbles and was totally baffled by the sample function. The marble diagram looks pretty random at first sight:

At first I thought - “Hey, that second sequence is getting totally ignored!”. But after I read the description I figured it out:

The first sequence’s elements is what sample emits, while the second sequence’s elements determine when sample emits. So in a way yes - the actual values A, B, C, D do get totally ignored.

When it was clear to me what sample does I started wondering if this function has any practical application :]

This brought me to creating a split lap timer app to test what sample can do for me. In the finished project I have a timer emitting time values (aka the first sequence) and I want to grab (or sample) the values whenever the user taps a button (aka the second sequence).

Here’s how the marble diagram looks like for the app setup:

And this is how the app looks like when finished:

Let’s build that app :]