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

import Foundation

class TransformOperation<Input, Output>: AsyncOperation, InputOperation, OutputOperation {
    private enum Executor {
        case callback((Input, @escaping (Output) -> Void) -> Void)
        case transform((Input) -> Output)
    }

    private let executor: Executor

    private init(input: Input? = nil, executor: Executor) {
        self.executor = executor

        super.init()
        self.input = input
    }

    convenience init(input: Input? = nil, _ block: @escaping (Input, @escaping (Output) -> Void) -> Void) {
        self.init(input: input, executor: .callback(block))
    }

    convenience init(input: Input? = nil, _ block: @escaping (Input) -> Output) {
        self.init(input: input, executor: .transform(block))
    }

    override func main() {
        guard let input = input else {
            self.finish()
            return
        }

        switch executor {
        case .callback(let block):
            block(input) { [weak self] (result) in
                self?.finish(with: result)
            }

        case .transform(let block):
            self.finish(with: block(input))
        }
    }
}