NetNewsWire/Evergreen/BatchUpdate.swift

66 lines
1.1 KiB
Swift
Raw Normal View History

2017-10-06 05:34:29 +02:00
//
// BatchUpdates.swift
// DataModel
//
// Created by Brent Simmons on 9/12/16.
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//
import Foundation
public typealias BatchUpdateBlock = () -> Void
public extension Notification.Name {
public static let BatchUpdateDidFinish = Notification.Name(rawValue: "BatchUpdateDidFinish")
2017-10-06 05:34:29 +02:00
}
final class BatchUpdate {
2017-10-06 05:38:54 +02:00
static let shared = BatchUpdate()
2017-10-06 05:34:29 +02:00
private var count = 0
var isPerforming: Bool {
get {
return count > 0
}
}
func perform(_ batchUpdateBlock: BatchUpdateBlock) {
incrementCount()
batchUpdateBlock()
decrementCount()
}
}
private extension BatchUpdate {
func incrementCount() {
count = count + 1
}
func decrementCount() {
count = count - 1
if count < 1 {
if count < 0 {
assertionFailure("Expected batch updates count to be 0 or greater.")
2017-10-06 05:34:29 +02:00
count = 0
}
count = 0
postBatchUpdateDidPerform()
}
}
func postBatchUpdateDidPerform() {
NotificationCenter.default.post(name: .BatchUpdateDidFinish, object: nil, userInfo: nil)
2017-10-06 05:34:29 +02:00
}
}