观察者模式
维基百科:
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems, in "event driven" software. Most modern languages such as C# have built in "event" constructs which implement the observer pattern components, for easy programming and short code.
观察者模式中,有一个主题(subject), 拥有一个观察(observer)者列表,当主题有状态改变,就会通知所有的观察者。
RxJava
RxJava 中主题对应数据源 Observable, 观察者对应 Observer. Observable 通过 subscribe 来登记一个观察者. 在一个数据源没有观察者时,这个数据源是处于冷冻状态,只有在一个观察者上来了,内部才会工作产生数据,数据才会流动起来。在数据源内部有状态改变,即(next,complete,error)事件时,会通知注册的观察者。
Observable.create(...).subscribe(object: Observer{
override fun onNext(data){
}
override fun onComplete(){
}
override fun onError(err){
}
})
网友评论