はじめに
RxSwiftの3.5.0からshare(replay:scope:)
が追加されました。
3.5.0未満のshare()
、shareReplay(_:)
、shareReplayLatestWhileConnected()
にどう対応しているのか書いていきます。
.share()
.share(scope: .forever)
.shareReplay(1)
.share(replay: 1, scope: .forever)
.shareReplayLatestWhileConnected()
.share(replay: 1, scope: .whileConnected)
参考
RxSwift/Observables/ShareReplayScope.swift
public func share(replay: Int = 0, scope: SubjectLifetimeScope)
-> Observable<E> {
switch scope {
case .forever:
switch replay {
case 0: return self.multicast(PublishSubject()).refCount()
default: return shareReplay(replay)
}
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()
}
}
}
追記
.share()
RxSwift/Observables/Multicast.swift
public func publish() -> ConnectableObservable<E> {
return self.multicast(PublishSubject())
}
public func share() -> Observable<E> {
return self.publish().refCount()
}
.shareReplayLatestWhileConnected()
RxSwift/Observables/ShareReplayScope.swift
public func shareReplayLatestWhileConnected() -> Observable<E> {
return ShareReplay1WhileConnected(source: self.asObservable())
}