DEV Community

Khoa Pham
Khoa Pham

Posted on

6 1

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top 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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay