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

import Foundation

/// A private type erasing observer that type casts the input operation type to the expected
/// operation type before calling the wrapped observer
class TransformOperationObserver<S: OperationProtocol>: OperationObserver {
    private let willExecute: (S) -> Void
    private let willFinish: (S) -> Void
    private let didFinish: (S) -> Void

    init<T: OperationObserver>(_ observer: T) {
        willExecute = Self.wrap(observer.operationWillExecute)
        willFinish = Self.wrap(observer.operationWillFinish)
        didFinish = Self.wrap(observer.operationDidFinish)
    }

    func operationWillExecute(_ operation: S) {
        willExecute(operation)
    }

    func operationWillFinish(_ operation: S) {
        willFinish(operation)
    }

    func operationDidFinish(_ operation: S) {
        didFinish(operation)
    }

    private class func wrap<U>(_ body: @escaping (U) -> Void) -> (S) -> Void {
        return { (operation: S) in
            if let transformed = operation as? U {
                body(transformed)
            } else {
                fatalError("\(Self.self) failed to cast \(S.self) to \(U.self)")
            }
        }
    }
}