Skip to content

Instantly share code, notes, and snippets.

@Nomad-Go
Created November 30, 2020 01:33
Show Gist options
  • Save Nomad-Go/a046d64f04438ca5f060c73b2d8c131e to your computer and use it in GitHub Desktop.
Save Nomad-Go/a046d64f04438ca5f060c73b2d8c131e to your computer and use it in GitHub Desktop.
Upload protocol
/// An object that will be transfered to or from S3
public protocol S3Transferable: class {
//A unique identifier for this object
var id: UUID { get }
//The key for the object in S3
var objectCloudKey: String { get }
//A CurrentValueSubject that will publish the progress as a Double and never fail
var progress: CurrentValueSubject<Double, Never> { get }
//The object returned by AWS that will give us access to some functionality and status.
var task: AWSS3TransferUtilityTask? { get set }
//The status of the transfer published by a CurrentValueSubject that will never fail.
var status: CurrentValueSubject<AWSS3TransferUtilityTransferStatusType, Never> { get }
//We will handle some combine stuff internally so I know I will need these publishers
var taskStatusKVOSubscription: AnyCancellable? { get set }
var taskStatusSubscription: AnyCancellable? { get set}
//Function to add a task
func add(task: AWSS3TransferUtilityTask)
}
extension S3Transferable {
//Default implementation
public func add(task: AWSS3TransferUtilityTask) {
//Store the task to to local variable
self.task = task
//Subscribe to the status property of the task using a combine publisher
self.taskStatusKVOSubscription = task.publisher(for: \.status).sink(receiveValue: { [weak self] (newStatus) in
//Send the new status value over the publisher
self?.status.send(newStatus)
})
//Subscribe to the status publisher
self.taskStatusSubscription = self.status.sink(receiveValue: { [weak self] (newStatus) in
switch newStatus {
case .cancelled, .error, .completed:
//So that when the upload is complete I can remove things and clean up.
self?.taskStatusKVOSubscription?.cancel()
self?.taskStatusKVOSubscription = nil
self?.taskStatusSubscription?.cancel()
self?.taskStatusSubscription = nil
self?.task = nil
default:
break
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment