Chapter 4 challenge

The question is: onComplete derives in the observable being disposed ?

func alert(title: String, text: String?) -> Observable {
return Observable.create { [weak self] observer in
let alertVC = UIAlertController(title: title, message: text, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: “Close”, style: .default, handler: {_ in
self?.present(alertVC, animated: true, completion: nil)
return Disposables.create {
DispatchQueue.main.async {
self?.dismiss(animated: true, completion: nil)

So if i comment observer.onCompleted() self?.dismiss… its not being called. From my understand the Disposable.create is just being called when the bag from the subscriber gets deallocated. :-?
And i also dont understand why it tries to dismiss the MainViewController in this line, since its the rootViewController of the application whats its intention?

@ivangodfather when an observable sequence terminates (e.g. it emits a completed or error events) all subscriptions to it are being disposed.

Therefore the logic here is that whenever the user taps on the “Close” button, the observable will emit a .completed event and any subscriptions to this alert’s observable will be disposed. Additionally - when the observable terminates it executes the code block you provide via Disposables.create(...) at the time when you create the observable. In that block you call dismiss(animated:completion:), which then dismisses the alert view.

So you have: Close button tap -> Observable completes -> any subscriptions disposed -> Disposables.create block dismisses the view

As for your second question, check the Apple docs about the dismiss(animated:completion) method, what it says is:

Dismisses the view controller that was presented modally by the view controller.

You should be calling this method on the view controller that presented the alert, so the code is correct

@icanzilb hi, my question is that can I use the PublishSubject instead

extension UIViewController {
    func showAlert(title: String?, message: String?) -> Observable<Void> {
        let publishSubject: PublishSubject<Void> = PublishSubject<Void>()
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let close = UIAlertAction(title: "Close", style: .cancel) { [weak self] _ in
            self?.dismiss(animated: true, completion: nil)
        present(alert, animated: true, completion: nil)
        return publishSubject

thank you

This topic was automatically closed after 166 days. New replies are no longer allowed.