1
\$\begingroup\$

I currently have a singleton that holds the translation objects in my app. View controllers can subscribe to its delegate so they can update their views if new translation objects have been added. This is what the class looks like

class TranslationItems {
    var delegate: TranslationItemsDelegate?

    static let shared = TranslationItems()

    private var set = Set<Translation>()

    // Public API

    public func add(object: Translation) {
        set.insert(object)
        delegate?.newItemAdded()
    }

    public func remove(object: Translation) {
        set.remove(object)
        delegate?.someItemDeleted()
    }

    public func getAll() -> [Translation] {
        return Array(set)
    }
}

protocol TranslationItemsDelegate {
    func newItemAdded()
    func someItemDeleted()
}

View controllers can use it like this:

// Add or remove objects
TranslationItems.shared.add(object: translation)

// Subscribe for notifications
TranslationItems.shared.delegate = self

Does this singleton class look ok or could it be improved?

\$\endgroup\$
3
\$\begingroup\$

The problem I see there is that when a new view controller subscribes, the previous one stops receiving notifications. There reason is because delegation is a one to one relationship.

"View controllers can subscribe to its delegate" That is wrong, it should be something like: "A view controller can subscribe to its delegate"

If that is what you want, then it is OK.

On the other hand, if you want to have several view controllers listening for those events, you need a 1 to many relationship. You can use NoticationCenter, KVO, Observables (RxSwift or Combine), or create your own solution, like:

addObserver removeObserver an array to save these observers (that conform to a protocol) and when triggering the event, just use observers.forEach { $0.sendEvent... }

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.