Disposable object that can be used to unsubscribe the observers.
RxSwift 주석 인용
리소스 정리에 사용되는 객체이다.
let fruits = ["🍎"," 🍇", "🍌"]
let subscription = Observable.from(fruits)
.subscribe {
print($0)
}
subscription.dispose()
dispose 를 호출하는 순간 자원이 정리되고, completed 이벤트 이전에 호출되었다면 completed 이벤트는 구독자에게 전달되지 않는다.
1초마다 1씩 증가한 정수를 방출하는 옵저버블이다. (0... 1... 2... 3... )
3초뒤에 dispose() 를 호출하여 자원을 정리한다.
/// 실행 취소에 사용하는 예
let subscription2 = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance).subscribe { elem in
print("Next", elem)
} onError: { error in
print("Error", error)
} onCompleted: {
print("Completed")
} onDisposed: {
print("Disposed")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
/// 호출하는 즉시 모든 리소스가 해제된다.
/// 그래서 next 다음에 completed 이벤트가 전달되지 않는다.
subscription2.dispose()
}
Next 0
Next 1
Next 2
Disposed
Disposable 을 DisposeBag 에 넣는 방식으로 자원을 관리한다.