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

extension CoreDataStack: AppStateReactorDelegate {

    fileprivate func registerBackgroundTask() {
        backgroundTask = UIApplication.shared.beginBackgroundTask {
            [unowned self] in
            self.endBackgroundTask()

    }

    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
        })
    }
}
