简体   繁体   English

如何将Realm通知抽象为带有闭包的通用结构?

[英]How can I abstract Realm notifications into a generic struct with a closure?

My view model currently contains the following code: 我的视图模型当前包含以下代码:

private let project = RLMProject()
var projectToken: NotificationToken? = nil

projectToken = project.getDatabase()?.objects(RLMProject.self).observe { changes in ...

With support in: 在以下方面提供支持:

final class RLMProject: Object, Decodable, DatabaseLayer { ... 
    typealias T = RLMProject
}

protocol DatabaseLayer {
    associatedtype T: Object

    func getDatabase() -> Realm?
}

extension DatabaseLayer {
    func getDatabase() -> Realm? {
        do {
            return try Realm(fileURL: userRealmFile)
        } catch let error {
            DDLogError("Database error: \(error)")
            return nil
        }
    }
...

I want to make the getDatabase() function private but am having trouble encapsulating the notification closure where the view model can still set it for any <T: Object> , without having to know the internals of anything about Realm. 我想将getDatabase()函数设为私有,但在封装通知闭包时遇到了麻烦,在该闭包中,视图模型仍可以为任何<T: Object>设置它,而不必了解有关Realm的任何内部信息。

Something from this: 由此产生的:

projectToken = project.getDatabase()?.objects(RLMProject.self).observe { [unowned self] ...

to this: 对此:

projectToken = project.setupNotificationToken { changes in ...

Seems I got it working. 似乎我可以使用了。

// Setup to observe Realm `CollectionChange` notifications
func setupNotificationToken(for observer: AnyObject, _ block: @escaping () -> Void) -> NotificationToken? {
    if let database = self.getDatabase() {
        return database.objects(T.self).observe { [weak observer] (changes: RealmCollectionChange) in
            if observer != nil {
                DDLogDebug("NotificationToken triggered on: \(observer!) for object: \(T.self)")
            }
            block()
        }
    } else {
        return nil
    }
}

Example: 例:

projectToken = project.setupNotificationToken(for: self) { [unowned self] in
    self.updateVC()
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM