Skip to content

Instantly share code, notes, and snippets.

@davidbjames
Created November 23, 2016 09:27
Show Gist options
  • Save davidbjames/5f99fdd53b4b0bb9366ee16b291b202f to your computer and use it in GitHub Desktop.
Save davidbjames/5f99fdd53b4b0bb9366ee16b291b202f to your computer and use it in GitHub Desktop.
Saving CKRecords via RxSwift
public struct ck_SaveRecordsCommand : ObservableTask {
public typealias Element = [CKRecord]
public var records:Element
public var options:TaskOptions?
public let cloudOptions:ck_Options
private var dependency:LoginDependency?
public init(_ records:Element, options:TaskOptions, cloudOptions:ck_Options = ck_Options()) {
self.records = records
self.options = options
if options.contains(.withDependencies) {
self.dependency = LoginDependency()
}
self.cloudOptions = cloudOptions
}
public func create() -> Observable<Element> {
let observable = Observable<Element>.create { observer in
let disposable = Disposables.create()
let operation = CKModifyRecordsOperation(recordsToSave: self.records, recordIDsToDelete: nil)
operation.database = self.cloudOptions.database
operation.savePolicy = self.cloudOptions.savePolicy
operation.isAtomic = true
operation.perRecordCompletionBlock = { (record:CKRecord?, error:Error?) in
guard error == nil else {
observer.on(.error(ck_Error.saveError(error)))
return
}
// NOTE: it's possible to use this for each record saved
// but it's not intuitive from a request perspective to
// handle each separately (it may complicate client code).
// Instead we just use this to report errors and fail early.
}
operation.modifyRecordsCompletionBlock = { (records:[CKRecord]?, deleteIds:[CKRecordID]?, error:Error?) in
if let records = records {
print("Saved: \(records)")
observer.on(.next(records))
}
observer.on(.completed)
}
self.cloudOptions.database.add(operation)
return disposable
}
if let dependency = self.dependency {
return dependency.fulfill().flatMap({ status in
return observable
})
} else {
return observable
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment