FRP and RxSwift Core Logic

2019-07-28  本文已影响0人  crystalztl

Talk about FRP

FRP(Functional Reactive Programming) is a programming paradigm for reactive programming (asynchronous dataflow programming) using the building blocks of functional programming. 

Let's talk about functional programming first. Functions are treated first class and can be parameter or return value.

Why functional programming is popular and what is the advantage?

1. low side effect

2. immutability

3. easy to test

4. generally, more concise

what is pure function?

Pure function always return same value given some input and it has no side effect. that is why it is easier to test and safer. As we know all operation related IO will cause side effect, and increase the system complexity and uncertainty. In a function with side effects, the function depends on or changes the state of the outside world, this would increase the difficulty of the testing and mess up the whole system. So functional programming promotes immutability. 

Always try to use immutable first in the practice. this is the same idea why swift recommend to use struct vs class. When there are multiple threads running in the system, immutable or constant would keep you safe, obviously. 

Function is the abstract of the world, in the complex system theory, y = f(a, b, c ...). Hence, most of the use cases, functions can represent the model of the bossiness logic and generally more concise. We can use swift to write quick sort in three to four lines:

func quicksort<T: Comparable>(_ a: [T]) -> [T] {

  guard a.count > 1 else { return a }

  let pivot = a[a.count/2]

  let less = a.filter { $0 < pivot }

  let equal = a.filter { $0 == pivot }

  let greater = a.filter { $0 > pivot }

  return quicksort(less) + equal + quicksort(greater)

}

And let us talk about Reactive Programming.

In my view, Reactive Programming is just a programming paradigm for the event handling and it is based on observer pattern.

Generally, when we design a system, we need to think about the event handling or event bus. In deep it is the art about passing information.

In iOS, normally there several ways to pass values.

1. Direct message. 

let vc = UIViewController()

vc.title = "My"    

this is the most direct way, people even cannot tell it when asked in a interview. But it is a powerful way. with a good design and clean code , you can use it to solve most of the use cases.

2. Notification

broadcast information is powerful however it could impact performance and could be messy

3. delegation 

Heavily been used in UIKit and could be messy. actually it is just callback.

4. target/action

Heavily been used in UIControl, based on OC dynamic feature.

5. KVO

could be replaced by Swift didSet feature.

6. block/closure/callback

Swift make functional more comfortable to use. however, could easily get a callback hell, especially in asynchronous programming.

And when there is heavily realtime UI event, the code could be complex. Hence Reactive programming, which has higher level abstract ability, focus more on the event / signal / stream/ sequence / observable, and their dependencies, to make front end business more clear and easy to write.

What is RP methodology ?

Keynotes about RP

1. Everything is event / signal / stream/ sequence / observable

2. React to event / signal / stream/ sequence / observable

3. Introduce one way bind and mutual way bind to iOS, this is normally a basic in front end technology.

4. signal could be combined and processed 

5. Create observable -> Observer Subscribe -> Send signal

I reference a diagram to show the idea of the RP

reference: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754#file-zmulticlickstream-png

RxCocoa example

       textField.rx.text.orEmpty.subscribe(onNext: { (text) in   print(text)  }).disposed(by: disposeBag)

let us step into rx source code to see how the event handler could be executed.

RxSwift example

    let ob =Observable.create{ (observer) ->Disposable in

            observer.onNext([1,2,3,4])

            observer.onCompleted()

            returnDisposables.create()

       }

            let_= ob.subscribe(onNext: { (text)in

                print("\(text)")

            })

When Create Observable, It creates AnonymousObservable: 

When observer subscribe, it create AnonymousObserver

reference from: https://www.jianshu.com/p/0e0703466483
上一篇下一篇

猜你喜欢

热点阅读