DEV Community

Khoa Pham
Khoa Pham

Posted on

Delegate with RxSwift

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

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(())
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

Usage

let lifeCycle = LifeCycle()
lifeCycle.didBecomeActive
  .bindNext({ [weak self] in
    self?.viewModel.reloadProfile()
  })
  .disposed(by: bag)
Enter fullscreen mode Exit fullscreen mode

Oldest comments (2)

Collapse
 
eonist profile image
Eon

Keep em coming Khoa Pham :D

Collapse
 
onmyway133 profile image
Khoa Pham

@Eon Hi, thanks 😇 You have good posts too