How to observe login state?

Viewed 38

I want View Controllers to be aware of every change in login status. Do I have to make a single tone and subscribe?

Singleton.swift

class Singleton {
    static let shared = Singleton()

    let isLogin: BehaviorRelay<Bool>

    private init() {
        isLogin = BehaviorRelay<Bool>(value: false)
    }
}

SomeViewController

class SomeVc: UIViewController {
    Sigleton.shared.isLogin.subscribe(.....)
}
1 Answers

No you don't need a Singleton...

Here's code I use in actual production. This code is in my application(_:didFinishLaunchingWithOptions:) method.

_ = UserDefaults.standard.rx.observe(String.self, "token")
    .map { $0 ?? "" }
    .filter { $0.isEmpty }
    .bind(onNext: presentScene(animated: true) { _ in
        LoginViewController.scene { $0.connect() }
    })

When the user logs in, I save a token in UserDefaults, when the user logs out, I remove it. The above code will present my LoginViewController when the user logs out.

If any other view controller needs to track the login state of the user, they can also subscribe to the token observable.

The presentScene(animated:_:) function and scene(_:) method both come from my CLE Library

Related