summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Operations/OutputOperation.swift
blob: 064d54a2e963f9503a13223ce793a25ba248f8c1 (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
//
//  OutputOperation.swift
//  MullvadVPN
//
//  Created by pronebird on 06/07/2020.
//  Copyright © 2020 Mullvad VPN AB. All rights reserved.
//

import Foundation

protocol OutputOperation: OperationProtocol {
    associatedtype Output

    var output: Output? { get set }

    func finish(with output: Output)
}

extension OutputOperation {
    func finish(with output: Output) {
        self.output = output
        self.finish()
    }
}

private var kOutputOperationAssociatedValue = 0
extension OutputOperation where Self: OperationSubclassing {
    var output: Output? {
        get {
            return synchronized {
                return AssociatedValue.get(object: self, key: &kOutputOperationAssociatedValue)
            }
        }
        set {
            synchronized {
                AssociatedValue.set(object: self, key: &kOutputOperationAssociatedValue, value: newValue)
            }
        }
    }
}

extension OperationProtocol where Self: OutputOperation {
    func addDidFinishBlockObserver(queue: DispatchQueue? = nil, _ block: @escaping (Self, Output) -> Void) {
        addDidFinishBlockObserver(queue: queue) { (operation) in
            if let output = operation.output {
                block(operation, output)
            }
        }
    }
}