响应式编程 php,二十二、响应式编程

响应式编程

响应式编程(Reactive Programming,简称RP),也是一种编程范式,于1997年提出,可以简化异步编程,提供更优雅的数据绑定。

一般与函数式融合在一起,所以也会叫做:函数响应式编程(Functional Reactive Programming,简称FRP)。

响应式框架

ReactiveCocoa:简称RAC,有Objective-C、Swift版本

ReactiveCocoa官网

github RAC

ReactiveX:简称Rx,有众多编程语言的版本,比如RxJava、RxKotlin、RxJS、RxCpp、RxPHP、RxGo、RxSwift等等

ReactiveX官网

github ReactiveX

源码

中文翻译文档

RxSwift安装及使用

cocoaPods安装

use_frameworks!

target 'target_name' do

pod 'RxSwift', '~> 5'

pod 'RxCocoa', '~> 5'

end

使用 导入模块

import RxSwift

import RxCocoa

RxSwift:Rx标准API的Swift实现,不包括任何iOS相关的内容

RxCocoa:基于RxSwift,给iOS的UI控件扩展了很多Rx特性

RxSwift的核心角色

Observable:负责发送事件(Event)

Observer:负责订阅Observable,监听Observable发送的事件(Event)

e1e81db90004

核心角色

Event有3种:

next :携带具体数据

error:携带错误信息,表明Observable终止,不会再发出事件

completed:表明Observable终止,不会再发出事件

public enum Event {

/// Next element is produced.

case next(Element)

/// Sequence terminated with an error.

case error(Swift.Error)

/// Sequence completed successfully.

case completed

}

创建、订阅Observable

创建Observable:

var observable = Observable.create { observer in

observer.onNext(1) //发消息

observer.onCompleted() //发消息完成

return Disposables.create()

}

//上面代码等价于下面每一行:

observable = Observable.just(1) //元素整体发⼀次,如果接受的是数组,就把数组整体发出去

observable = Observable.of(1)

observable = Observable.from([1]) //如果接受的是数组,就把数组元素一个一个发出去

订阅Observable(接收消息)

observable.subscribe { event in //传个闭包表达式来订阅

switch event {

case .next(let element):

print("next",element)

case .error(let error):

print("error",error)

case .completed:

print("completed")

}

}.dispose() //订阅完之后⻢上取消订阅,只订阅⼀次

//上面写法和下面等价:

observable.subscribe(onNext: { //传个闭包表达式来订阅

print("next", $0)

}, onError: {

print("error", $0)

}, onCompleted: {

print("completed")

}, onDisposed: {

print("dispose")

}).dispose() //订阅完之后⻢上取消订阅,只订阅⼀次

根据如下例子,理解of和from的区别:

var observable = Observable.create { observer in

observer.onNext(1)

observer.onNext(2)

observer.onNext(3)

observer.onCompleted()

return Disposables.create()

}

//等价于

observable = Observable.of(1, 2, 3) //多个元素,发三次

observable = Observable.from([1, 2, 3]) //数组,发三次

取消订阅(Disposable)

每当Observable被订阅时,都会返回一个Disposable实例,当调用Disposable的dispose就相当于取消订阅。

在不需要再接收事件时,建议取消订阅,释放资源,有3种常见方式取消订阅。

//立即取消订阅(一次性订阅)

observable.subscribe { event in

print(event)

}.dispose()

//当bag销毁(deinit)时,会自动调用Disposable实例的dispose

observable.subscribe { event in

print(event)

}.disposed(by: bag)

//self销毁时(deinit)时,会自动调用Disposable实例的dispose

//takeUntil是保留到什么时候的意思

let _ = observable.takeUntil(self.rx.deallocated).subscribe { event in

print(event)

}

创建Observer

Observer:

//创建接收者

let observer = AnyObserver.init { event in

switch event {

case .next(let data):

print(data)

case .completed:

print("completed")

case .error(let error):

print("error", error)

}

}

Observable.just(1).subscribe(observer).dispose()

Binder:

//Binder内部也有⼀个Observer,绑定⼀个就相当于订阅了

let binder = Binder(label) { label, text in

label.text = text

}

//将"数值是1"绑定到label.text上

Observable.just(1).map { "数值是\($0)" }.subscribe(binder).dispose()

//等价于下面

Observable.just(1).map { "数值是\($0)" }.bind(to: binder).dispose()

使用定时器让button每隔1秒钟隐藏、显示一次,如下:

//创建Observable

//2秒之后,每隔1秒钟在主线程发消息

let observable = Observable.timer(.second(2)), period: .second(1), scheduler: MainScheduler.instance)

let binder = Binder(button) { button, value in

button.isHidden = value

}

//订阅Observable

//bind内部其实就是订阅

observable.map { $0 % 2 == 0 }.bind(to: binder).disposed(by: bag) //int转Bool

上面是把

math?formula=0%20%25%202%20%3D%3D%200%20%E7%BB%91%E5%AE%9A%E5%88%B0binder%E4%B8%8A%E9%9D%A2%EF%BC%8C%E9%82%A3%E4%B9%88%E8%83%BD%E4%B8%8D%E8%83%BD%E6%8A%8A0 % 2 == 0 绑定到button.rx.hidden上面呢?

//给UIView扩展hidden属性

extension Reactive where Base: UIView {

var hidden: Binder {

Binder(base) { view, value in

view.isHidden = value

}

}

}

let observable = Observable.interval(.seconds(1), scheduler: MainScheduler.instance)

observable.map { $0 % 2 == 0 }.bind(to: button.rx.hidden).disposed(by: bag)

状态监听

传统的状态监听

传统的常见监听方案有:

KVO

Target-Action

Notification

Delegate

Block Callback

传统方案经常会出现错综复杂的依赖关系、耦合性较高,还需要编写重复的非业务代码。

RxSwift的状态监听

button:

//订阅button的点击事件

button.rx.tap.subscribe(onNext: {

print("按钮被点击了1")

}).disposed(by: bag)

tableview:

let data = Observable.just([

Person(name: "Jack", age: 10),

Person(name: "Rose", age: 20)

])

//数据源绑定到tableview上,数据源改变tableview会刷新

data.bind(to: tableView.rx.items(cellIdentifier: "cell")) { row, person, cell in

cell.textLabel?.text = person.name

cell.detailTextLabel?.text = "\(person.age)"

}.disposed(by: bag)

cell:

//订阅cell的点击⽅法

tableView.rx.modelSelected(Person.self)

.subscribe(onNext: { person in

print("点击了", person.name)

}).disposed(by: bag)

属性:

class Dog: NSObject {

@objc dynamic var name: String?

}

//Rx形式的KVO监听属性

dog.rx.observe(String.self, "name")

.subscribe(onNext: { name in

print("name is", name ?? "nil")

}).disposed(by: bag)

dog.name = "larry"

dog.name = "wangwang"

通知:

//Rx形式的通知监听

NotificationCenter.default.rx

.notification(UIApplication.didEnterBackgroundNotification)

.subscribe(onNext: { notification in

print("APP进入后台", notification)

}).disposed(by: bag)

既是Observable,又是Observer

//slider.rx.value是接收者

Observable.just(0.8).bind(to: slider.rx.value).dispose()

//现在slider.rx.value是发送者,textField.rx.text是接受者

slider.rx.value.map {

"当前数值是:\($0)"

}.bind(to: textField.rx.text).disposed(by: bag)

//现在textField.rx.text是发送者,然后再订阅它的消息

textField.rx.text

.subscribe(onNext: { text in

print("text is", text ?? "nil")

}).disposed(by: bag)

诸如UISlider.rx.value、UTextField.rx.text这类属性值,既是Observable,又是Observer,它们是RxCocoa.ControlProperty类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP Reactive Programming by Martin Sikora English | 24 Mar. 2017 | ASIN: B01IBPRAA8 | 364 Pages | AZW3 | 3.46 MB Key Features Develop an interesting multiplayer browser game written in RxJS and re-implement it using RxPHP Enhance existing reactive applications by building a CLI tool combining Symfony Console Implement Gearman and Rabbit MQ for asynchronous communication Book Description Reactive Programming helps us write code that is concise, clear, and readable. Combining the power of reactive programming and PHP, one of the most widely used languages, will enable you to create web applications more pragmatically. PHP Reactive Programming will teach you the benefits of reactive programming via real-world examples with a hands-on approach. You will create multiple projects showing RxPHP in action alone and in combination with other libraries. The book starts with a brief introduction to reactive programming, clearly explaining the importance of building reactive applications. You will use the RxPHP library, built a reddit CLI using it, and also re-implement the Symfony3 Event Dispatcher with RxPHP. You will learn how to test your RxPHP code by writing unit tests. Moving on to more interesting aspects, you will implement a web socket backend by developing a browser game. You will learn to implement quite complex reactive systems while avoiding pitfalls such as circular dependencies by moving the RxJS logic from the frontend to the backend. The book will then focus on writing extendable RxPHP code by developing a code testing tool and also cover Using RxPHP on both the server and client side of the application. With a concluding chapter on reactive programming practices in other languages, this book will serve as a complete guide for you to start writing reactive applications in PHP. What you will learn How to work with the RxPHP library and see what it offers via many examples Use the RxPHP library in combination with Symfony Console The different approaches

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值