Functional responsive programming

Functional responsive programming

image

Functional responsive programming is a programming paradigm. It is a programming method that manipulates data sequences by building functions and then responds to these sequences. It combines functional programming and reactive programming

Functional programming is a programming paradigm that requires us to pass functions as parameters or return them as return values. We can get the desired result by combining different functions.

Advantages of function trial programming

  • flexible
  • High reuse
  • concise
  • Easy to maintain
  • Adapt to various needs

Functional Programming-> Functional Responsive Programming

Think of a button click event as a sequence:

image

// 假设用户在进入页面到离开页面期间,总共点击按钮 3 次

// 按钮点击序列
let taps: Array<Void> = [(), (), ()]
 // 每次点击后弹出提示框 taps.forEach { showAlert() }

It is ideal to handle click events in this way, but the problem is that the elements (click events) in this sequence are generated asynchronously. Traditional sequences cannot describe the situation in which such elements are generated asynchronously. In order to solve this problem, a listenable sequence Observable was generated. It is also a sequence, but the elements in this sequence can be generated synchronously or asynchronously:

image

// 按钮点击序列
let taps: Observable<Void> = button.rx.tap.asObservable()

// 每次点击后弹出提示框
taps.subscribe(onNext: { showAlert() })

Here taps is the sequence of button click events. Then we respond to each click event by popping up a prompt box. This programming method is called responsive programming. We combine functional programming and reactive programming to get functional reactive programming:

image

passwordOutlet.rx.text.orEmpty
    .map { $0.characters.count >= minimalPasswordLength }
    .bind(to: passwordValidOutlet.rx.isHidden)
    .disposed(by: disposeBag)

We use different construction functions to create the required data sequence. Finally, respond to this sequence in an appropriate way. This is functional reactive programming.

Data binding (subscription)

image

An important concept in RxSwift is data binding (subscription). It means binding the listenable sequence to the observer:

Let's compare these two pieces of code:

let image: UIImage = UIImage(named: ...)
imageView.image = image


let image: Observable<UIImage> = ... image.bind(to: imageView.rx.image) 

We are very familiar with the first piece of code, which is to set a single image to the imageView.

The second piece of code "syncs" a sequence of pictures to the imageView. The pictures in this sequence can be generated asynchronously. The image defined here is the blue part of the image above (you can monitor the sequence), and imageView.rx.image is the orange part of the image above (the observer). And this "synchronization mechanism" is data binding (subscription).

Guess you like

Origin www.cnblogs.com/liuxiaokun/p/12680485.html