Disposables
๐๏ธ Disposables โ ๋ฉ๋ชจ๋ฆฌ ๋์ ์๋ RxSwift ์ฌ์ฉ๋ฒ
โ๊ตฌ๋ ์ ๊ณง ๋ฆฌ์์ค.โ ํด์ง(Dispose)ํ์ง ์์ผ๋ฉด ObserverยทObservableยทClosure ๋ชจ๋ ๋ฉ๋ชจ๋ฆฌ์ ๋จ์ต๋๋ค.
์ด ์ฅ์์๋ Disposable
ํ๋กํ ์ฝ๊ณผ DisposeBag
, ๊ทธ๋ฆฌ๊ณ ์๋ ํด์ ์คํผ๋ ์ดํฐ๋ฅผ ํตํด ๋์ ์๋ Rx ์ฝ๋๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ์ ๋ค๋ฃน๋๋ค.
1๏ธโฃ Disposable ๊ธฐ๋ณธ ๊ฐ๋
public protocol Disposable {
func dispose()
}
์ญํ : Observable ๊ตฌ๋ ์ ์ทจ์ํ๊ณ ๊ด๋ จ ๋ฆฌ์์ค๋ฅผ ํด์ .
์์ฑ ๊ฒฝ๋ก:
subscribe()
๋ฉ์๋๋ ํญ์Disposable
์ ๋ฐํ.
let disposable = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
.subscribe(onNext: { print($0) })
// 5์ด ํ ์๋ ํด์
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
disposable.dispose()
}
์ฃผ์: ์๋
dispose()
ํธ์ถ์ ์์ผ๋ฉด Hot Observable๊ณผ Timer ๋ฑ์ด ์์ํ ์ด์์์ด ๋์ยท๋ฐฐํฐ๋ฆฌ ์๋ชจ ๊ฐ๋ฅ.
2๏ธโฃ DisposeBag โ ์์ง ํ ์ผ๊ด dispose
์ค์ฝํ ๋จ์ ๊ด๋ฆฌ
Bag์ด deinited ๋๋ฉด ๋ด๋ถ ๋ชจ๋ Disposable ์๋ ํด์
์ผ๋ฐ ํจํด
ViewControllerยทViewModel์ let bag = DisposeBag()
์์ฑ
ARC ํ์ฉ
ํด๋ก์ retain cycle ์์ด ์๋ช ์ฃผ๊ธฐ ์ผ์น
class LoginViewModel {
private let bag = DisposeBag()
func bind(input: Input) {
input.loginTap
.flatMapLatest(api.login)
.subscribe()
.disposed(by: bag) // โ
}
}
3๏ธโฃ ๊ธฐํ Disposable ๊ตฌํ์ฒด
SerialDisposable
๋ด๋ถ Disposable์ ๊ต์ฒด ๊ฐ๋ฅ (์: ์ฌ์๋ ์ ์ด์ ์์ฒญ ์ทจ์)
CompositeDisposable
์ฌ๋ฌ Disposable์ ๋ฌถ์ด ์ผ๊ด ํด์ (DisposeBag
Swift ๋ฒ์ )
RefCountDisposable
์ฐธ์กฐ ์นด์ดํธ ๊ธฐ๋ฐ, ๋ง์ง๋ง dispose ๋ ์ค์ ํด์
let serial = SerialDisposable()
searchQuery
.flatMapLatest(api.search) // ์ ๊ฒ์๋ง๋ค ์ด์ ์์ฒญ out
.subscribe()
.disposed(by: serial)
4๏ธโฃ ์๋ ํด์ ์คํผ๋ ์ดํฐ
take(_:)
n๊ฐ ์์ ํ completed
๋ฒํผ ์ฒซ 1ํ ์ด๋ฒคํธ ์ฒ๋ฆฌ
takeUntil(_:)
Trigger Observable emit ์ completed
ViewWillDisappear์ ์ฐ๋
timeout(_:)
๊ธฐํ ๋ด ์ด๋ฒคํธ ์์ผ๋ฉด error
์๋ฒ ์๋ต ๋๊ธฐ
single()
์ฒซ ์์ + completed
๊ฒฐ๊ณผ 1๊ฐ ๋ณด์ฅ API
viewWillDisappearSignal
.subscribe(onNext: { _ in print("Bye") })
.disposed(by: bag)
observable
.takeUntil(viewWillDisappearSignal)
.subscribe()
.disposed(by: bag) // ์๋ ์ข
๋ฃ
5๏ธโฃ ๋ฉ๋ชจ๋ฆฌ ๋์ ์ฒดํฌ ํ
Debug Memory Graph(
โงโI
) ํ ViewController ์ธ์คํด์ค ํ์ธ.Xcode
Allocations
Instrument์์ Live Count ์ถ์ .RxSwiftCommunity์ LeakDetector ์ฌ์ฉ (
rx.disableLeakDetection = false
).
6๏ธโฃ Best Practices Checklist โ
7๏ธโฃ Mini Quiz
DisposeBag
๋์SerialDisposable
์ด ๋ ์ ํฉํ ์๋๋ฆฌ์ค๋?take(1)
๊ณผsingle()
์ ๋์ ์ฐจ์ด ํ ์ค ์์ฝ.ViewController deinit์ด ํธ์ถ๋์ง ์์ ๋ ํ์ธํด์ผ ํ ์ธ ๊ฐ์ง ํญ๋ชฉ์?
Last updated