blob: eccb7f63abdf17109d669871945f38cb7ea5dc56 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
//
// OperationBlockObserver.swift
// MullvadVPN
//
// Created by pronebird on 06/07/2020.
// Copyright © 2020 Mullvad VPN AB. All rights reserved.
//
import Foundation
class OperationBlockObserver<OperationType: OperationProtocol>: OperationObserver {
private var willFinish: ((OperationType) -> Void)?
private var didFinish: ((OperationType) -> Void)?
let queue: DispatchQueue?
init(queue: DispatchQueue? = nil, willFinish: ((OperationType) -> Void)? = nil, didFinish: ((OperationType) -> Void)? = nil) {
self.queue = queue
self.willFinish = willFinish
self.didFinish = didFinish
}
func operationWillFinish(_ operation: OperationType) {
if let willFinish = self.willFinish {
scheduleEvent {
willFinish(operation)
}
}
}
func operationDidFinish(_ operation: OperationType) {
if let didFinish = self.didFinish {
scheduleEvent {
didFinish(operation)
}
}
}
private func scheduleEvent(_ body: @escaping () -> Void) {
if let queue = queue {
queue.async(execute: body)
} else {
body()
}
}
}
extension OperationProtocol {
func addDidFinishBlockObserver(queue: DispatchQueue? = nil, _ block: @escaping (Self) -> Void) {
addObserver(OperationBlockObserver(queue: queue, didFinish: block))
}
}
|