FRP with RxSwift examples (#2)

TuyenBQ
3 min readSep 27, 2016

--

In previous blog, we’ve got the first example with RxSwift, got the way to Rx did and integrated with built-in components like UIScrollBar. If you did not, let’s take a look at this.

For this blog, we gonna continuous explore something new with Rx via RxSwift. Let’s dig in right now. As you may remember, in RxSwift, there are some concepts: Subject,BehaviorSubject,ReplaySubject,PublishSubject and so on. Question is: What is the diff on these concepts?

On the RxSwift’s docs, defined as: http://cocoadocs.org/docsets/RxSwift/2.6.0/RxSwift/Subjects.html#/s:C7RxSwift8Variable

However basically, here is definition:

Subject — Observable and Observer at once. Basically it can observe and be observed.
BehaviorSubject — When you subscribe to it, you will get the latest value emitted by the Subject, and then the values emitted after the subscription.
PublishSubject — When you subscribe to it, you will only get the values that were emitted after the subscription.
ReplaySubject — When you subscribe to it, you will get the values that were emitted after the subscription, but also values that were emitted before the subscription. How many old values will you get? It depends on the buffer size ofReplaySubject you subscribe to. You specify it in init of the Subject.

Not quite hard to understand them. But how can we apply to real world?. For getting started example, we will use Variable(is wrapper around BehaviorSubject.)

We will create a simple example like find even or odd number with an input number. Don’t miss to use CocoaPods:

For that, create a new proj and on Main.storyboard, make it such as:

And then, declare a view model, the view model represents model to view.

As you can see, we have 2 variables, the first one holds value which will bind to itself, the last one will get the value holding of numberVariable to calculate and return result expectation.

Here is full view model looks like:

More detail:

  1. Transform our variable into Observable.
  2. Map every new value of TextField.
  3. Calculate and return result.

Simple?

Go back ViewControler.swift

Ignore all thing you seen, please focus to checkEvenNumber function, we have 2 part.

I. TextField’s value:

  1. Get text value with rx_observe
  2. Transfer it to a Variable
  3. Avoid retain cycle with disposeBag

II. Subscribe new thing:

  1. Subscribe each new value come
  2. Assign new value to resultLabel
  3. Avoid retain cycle with disposeBag

Almost done, build and run your sample.

With this simple example, we basically understood using RxSwift to process simple data. Use Variable and Observable to transfer and get some thing. Besides of this, we also would use Driver, look at this :

It’s enough today. I hope you’ve enjoyed this blog. If you have any questions, comments or feedback please leave it below.

Peace ✌

--

--