     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?

    }

    fileprivate func endBackgroundTask() {
        UIApplication.shared.endBackgroundTask(backgroundTask!)
        backgroundTask = UIBackgroundTaskIdentifier(rawValue: UIBackgroundTaskIdentifier.invalid.rawValue)
    }

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

extension CoreDataStack: AppStateReactorDelegate {

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