How to do delegate with RxSwift

Issue #12

We can use DelegateProxy and DelegateProxyType to make beautiful delegate with RxSwift. But in some other cases, we can just create a custom class with PublishSubject.

This is how we can make rx out of UIApplication life cycle events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class LifeCycle {
let didEnterBackground = PublishSubject<Void>()
let willEnterForeground = PublishSubject<Void>()
let didBecomeActive = PublishSubject<Void>()
let willResignActive = PublishSubject<Void>()

init() {
let center = NotificationCenter.default
let app = UIApplication.shared

center.addObserver(forName: Notification.Name.UIApplicationDidEnterBackground,
object: app, queue: .main, using: { [weak self] _ in
self?.didEnterBackground.onNext(())
})

center.addObserver(forName: Notification.Name.UIApplicationWillEnterForeground,
object: app, queue: .main, using: { [weak self] _ in
self?.willEnterForeground.onNext(())
})

center.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive,
object: app, queue: .main, using: { [weak self] _ in
self?.didBecomeActive.onNext(())
})

center.addObserver(forName: Notification.Name.UIApplicationWillResignActive,
object: app, queue: .main, using: { [weak self] _ in
self?.willResignActive.onNext(())
})
}
}

Usage

1
2
3
4
5
6
let lifeCycle = LifeCycle()
lifeCycle.didBecomeActive
.bindNext({ [weak self] in
self?.viewModel.reloadProfile()
})
.disposed(by: bag)

Comments