Skip to content

Instantly share code, notes, and snippets.

@mimthath4
Last active January 29, 2020 06:14
Show Gist options
  • Save mimthath4/928faf0422d7b2d476fc30b8d43f1ff7 to your computer and use it in GitHub Desktop.
Save mimthath4/928faf0422d7b2d476fc30b8d43f1ff7 to your computer and use it in GitHub Desktop.
import Foundation
private let bgQueue = DispatchQueue(label: "MIUsecase")
/// Provide implementation for the execute method and then
/// call perform to get response in main thread
/// call execute to get response in background thread
public protocol MIUsecase: class {
associatedtype MIUsecaseRequest
associatedtype MIUsecaseResponse
/// performs the usecase request in a common background queue
/// and the response callback is in main thread
func perform(_ request: MIUsecaseRequest, and callback: @escaping (MIUsecaseResponse) -> Void)
/// executes the usecase request in a background thread
/// and the response callback is in the same background thread
func execute(_ request: MIUsecaseRequest, and callback: @escaping (MIUsecaseResponse) -> Void)
/// used to perform callback in the main queue
func invoke(_ callback: @escaping (MIUsecaseResponse) -> Void, using result: MIUsecaseResponse)
}
public extension MIUsecase {
func perform(_ request: MIUsecaseRequest, and callback: @escaping (MIUsecaseResponse) -> Void) {
bgQueue.async { [weak self] in
self?.execute(request) { [weak self] result in
self?.invoke(callback, using: result)
}
}
}
func invoke(_ callback: @escaping (MIUsecaseResponse) -> Void, using result: MIUsecaseResponse) {
if Thread.isMainThread {
callback(result)
return
}
DispatchQueue.main.async {
callback(result)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment