Skip to content

Commit

Permalink
Move notificationTokens out of BackgroundWorker
Browse files Browse the repository at this point in the history
  • Loading branch information
Sol Cai authored and caiyue1993 committed Oct 2, 2019
1 parent 58e01c6 commit 3ac19b4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
2 changes: 0 additions & 2 deletions IceCream/Classes/BackgroundWorker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ public class BackgroundWorker: NSObject {

static let shared = BackgroundWorker()

var notificationTokens = [NotificationToken]()

private var thread: Thread?
private var block: (() -> Void)?

Expand Down
23 changes: 16 additions & 7 deletions IceCream/Classes/SyncObject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,11 @@ extension SyncObject: Syncable {
/// https://realm.io/docs/swift/latest/#objects-with-primary-keys
realm.beginWrite()
realm.add(object, update: .modified)
try! realm.commitWrite(withoutNotifying: BackgroundWorker.shared.notificationTokens)
if let token = self.notificationToken {
try! realm.commitWrite(withoutNotifying: [token])
} else {
try! realm.commitWrite()
}
}
}

Expand All @@ -95,7 +99,11 @@ extension SyncObject: Syncable {
CreamAsset.deleteCreamAssetFile(with: recordID.recordName)
realm.beginWrite()
realm.delete(object)
try! realm.commitWrite(withoutNotifying: BackgroundWorker.shared.notificationTokens)
if let token = self.notificationToken {
try! realm.commitWrite(withoutNotifying: [token])
} else {
try! realm.commitWrite()
}
}
}

Expand All @@ -104,7 +112,7 @@ extension SyncObject: Syncable {
public func registerLocalDatabase() {
BackgroundWorker.shared.start {
let realm = try! Realm(configuration: self.realmConfiguration)
let notificationToken = realm.objects(T.self).observe({ [weak self](changes) in
self.notificationToken = realm.objects(T.self).observe({ [weak self](changes) in
guard let self = self else { return }
switch changes {
case .initial(_):
Expand All @@ -119,20 +127,21 @@ extension SyncObject: Syncable {
break
}
})

BackgroundWorker.shared.notificationTokens.append(notificationToken)
}
}

public func cleanUp() {
BackgroundWorker.shared.start {
let realm = try! Realm(configuration: self.realmConfiguration)
let objects = realm.objects(T.self).filter { $0.isDeleted }


var tokens: [NotificationToken] = []
self.notificationToken.flatMap { tokens = [$0] }

realm.beginWrite()
objects.forEach({ realm.delete($0) })
do {
try realm.commitWrite(withoutNotifying: BackgroundWorker.shared.notificationTokens)
try realm.commitWrite(withoutNotifying: tokens)
} catch {

}
Expand Down

0 comments on commit 3ac19b4

Please sign in to comment.