我已经阅读了Rx Swift / ShareReplayScope.swift文件,但有点难以理解. public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) - ObservableE { switch scope { case .forever: switch replay { case 0: return
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) -> Observable<E> { switch scope { case .forever: switch replay { case 0: return self.multicast(PublishSubject()).refCount() default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() } case .whileConnected: switch replay { case 0: return ShareWhileConnected(source: self.asObservable()) case 1: return ShareReplay1WhileConnected(source: self.asObservable()) default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() } } }
0,1和默认值,有什么区别?为什么将1与defalut分开?
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable }
如何锁定工作,最困难的是这个功能.封锁的obserables如何正确连接到他们的观察者.
您可以在下面获得有关shareReplay功能的信息.分享()
如您所知,共享功能共享Observable的订阅.这样您就不需要每次都创建多个可观察的实例.
只需创建一个observable并共享重播.它将允许在这个可共享的可观察对象中执行下一个操作.即filter(),subscribe()等.
但是share()的问题是,它在订阅之前不提供值.
shareReplay()
其中shareReplay()保留最后几个发射值的缓冲区,并且可以在订阅时将它们提供给新的观察者.