Closed HAKASHUN closed 8 years ago
【RxSwift】viewWillAppear等が呼ばれた時のトリガーを作ってみる
class SampleViewController: UIViewController {
private func trigger(selector: Selector) -> Observable<Void> {
return rx_sentMessage(selector).map { _ in () }.shareReplay(1)
}
var viewWillAppearTrigger: Observable<Void> {
return trigger(#selector(self.viewWillAppear(_:)))
}
var viewDidAppearTrigger: Observable<Void> {
return trigger(#selector(self.viewDidAppear(_:)))
}
var viewWillDisappearTrigger: Observable<Void> {
return trigger(#selector(self.viewWillDisappear(_:)))
}
var viewDidDisappearTrigger: Observable<Void> {
return trigger(#selector(self.viewDidDisappear(_:)))
}
private let disposeBag = DisposeBag()
func viewDidLoad() {
super.viewDidLoad()
viewWillAppearTrigger
.skip(1) //初回はスキップ
.subscribeNext { _ in
print("viewWillAppear")
}
.addDisposableTo(disposeBag)
}
}
class SampleViewController: UIViewController {
let rx_viewWillAppear:Observable<Void> = PublishSubject()
let rx_viewDidAppear:Observable<Void> = PublishSubject()
let rx_viewWillDisappear:Observable<Void> = PublishSubject()
let rx_viewDidDisappear:Observable<Void> = PublishSubject()
private let disposeBag = DisposeBag()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
(rx_viewWillAppear as? PublishSubject)?.on(.Next())
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
(rx_viewDidAppear as? PublishSubject)?.on(.Next())
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
(rx_viewWillAppear as? PublishSubject)?.on(.Next())
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
func viewDidLoad() {
super.viewDidLoad()
rx_viewWillAppear
.skip(1) //初回はスキップ
.subscribeNext { _ in
print("viewWillAppear")
}
.addDisposableTo(disposeBag)
}
}
やり方は2パターンあります。