Tunko Development Diary

RxSwift) sharing Subscription Operator (refCount) 본문

Development/RxSwift

RxSwift) sharing Subscription Operator (refCount)

Tunko 2022. 6. 8. 16:36

RefCount

extension ConnectableObservableType {
    public func refCount() -> Observable<Element> {
        RefCount(source: self)
    }
}

RefCount 는 ConnectableObservableType 형에만 따로 구현되어있습니다. 구현된것을 보면 파라미터는 없고 Observable<Element> 을 리턴합니다.

RefCount는 옵저버블입니다.

내부에 ConnectableObservable을 유지하면서 새로운 구독자가 생성되는 시점에 자동으로 connect() 시켜줍니다.

let disposeBag = DisposeBag()
let oneSecondObservable = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
    .take(5)
    .publish()
    .refCount()
    .debug()
let observer1 = oneSecondObservable.subscribe { print("🍎 : ", $0) }

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    observer1.dispose()
}

DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
    let observer2 = oneSecondObservable
        .subscribe { print("🥝 : ", $0) }

    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
        observer2.dispose()
    }
}

출력

2022-06-08 11:28:40.158: refCount.playground:59 (__lldb_expr_88) -> subscribed
2022-06-08 11:28:41.162: refCount.playground:59 (__lldb_expr_88) -> Event next(0)
🍎 :  next(0)
2022-06-08 11:28:42.162: refCount.playground:59 (__lldb_expr_88) -> Event next(1)
🍎 :  next(1)
2022-06-08 11:28:43.161: refCount.playground:59 (__lldb_expr_88) -> Event next(2)
🍎 :  next(2)
2022-06-08 11:28:43.298: refCount.playground:59 (__lldb_expr_88) -> isDisposed
2022-06-08 11:28:45.297: refCount.playground:59 (__lldb_expr_88) -> subscribed
2022-06-08 11:28:46.299: refCount.playground:59 (__lldb_expr_88) -> Event next(0)
🥝 :  next(0)
2022-06-08 11:28:47.298: refCount.playground:59 (__lldb_expr_88) -> Event next(1)
🥝 :  next(1)
2022-06-08 11:28:48.298: refCount.playground:59 (__lldb_expr_88) -> Event next(2)
🥝 :  next(2)

출력 로그를 보면 🍎  옵저버블이 isDisposed 된후에 🥝  옵저버블이 다시 구독을 시작해서 새로운 시퀀스로 이벤트를 방출합니다

반응형
Comments