 extension CoreDataStack: AppStateReactorDelegate {
 
     fileprivate func registerBackgroundTask() {
+        guard backgroundTask == .invalid else { return }
         backgroundTask = UIApplication.shared.beginBackgroundTask {
             [unowned self] in
             self.endBackgroundTask()

    public var rootContext: NSManagedObjectContext
    #if os(iOS)
    fileprivate let appStateReactor: AppStateReactor
    var backgroundTask: UIBackgroundTaskIdentifier?
    #endif
    var modelURL: URL
    var securityApplicationGroupIdentifier: String?

    }

    fileprivate func endBackgroundTask() {
        guard backgroundTask != .invalid else { return }
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = .invalid
    }

    public func didReceiveStateChange(_ appStateReactor: AppStateReactor) -> Void {
        registerBackgroundTask()
        return save({ (error: NSError?) in
            self.endBackgroundTask()
            self.backgroundTask = .invalid
        })
    }
}
