summaryrefslogtreecommitdiffhomepage
path: root/ios/Operations/OperationObserver.swift
blob: 36740dd729ad980a30eda3b48bab53c750c1f39a (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
53
54
55
56
57
58
59
60
61
62
63
//
//  OperationObserver.swift
//  Operations
//
//  Created by pronebird on 30/05/2022.
//  Copyright © 2026 Mullvad VPN AB. All rights reserved.
//

import Foundation

public protocol OperationObserver {
    func didAttach(to operation: Operation)
    func operationDidStart(_ operation: Operation)
    func operationDidCancel(_ operation: Operation)
    func operationDidFinish(_ operation: Operation, error: Error?)
}

/// Block based operation observer.
public class OperationBlockObserver<OperationType: Operation>: OperationObserver {
    public typealias VoidBlock = (OperationType) -> Void
    public typealias FinishBlock = (OperationType, Error?) -> Void

    private let _didAttach: VoidBlock?
    private let _didStart: VoidBlock?
    private let _didCancel: VoidBlock?
    private let _didFinish: FinishBlock?

    public init(
        didAttach: VoidBlock? = nil,
        didStart: VoidBlock? = nil,
        didCancel: VoidBlock? = nil,
        didFinish: FinishBlock? = nil
    ) {
        _didAttach = didAttach
        _didStart = didStart
        _didCancel = didCancel
        _didFinish = didFinish
    }

    public func didAttach(to operation: Operation) {
        if let operation = operation as? OperationType {
            _didAttach?(operation)
        }
    }

    public func operationDidStart(_ operation: Operation) {
        if let operation = operation as? OperationType {
            _didStart?(operation)
        }
    }

    public func operationDidCancel(_ operation: Operation) {
        if let operation = operation as? OperationType {
            _didCancel?(operation)
        }
    }

    public func operationDidFinish(_ operation: Operation, error: Error?) {
        if let operation = operation as? OperationType {
            _didFinish?(operation, error)
        }
    }
}