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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
//
// InputOperation.swift
// MullvadVPN
//
// Created by pronebird on 06/07/2020.
// Copyright © 2020 Mullvad VPN AB. All rights reserved.
//
import Foundation
protocol InputOperation: OperationProtocol {
associatedtype Input
/// When overriding `input` in Subclasses, make sure to call `operationDidSetInput`
var input: Input? { get set }
func operationDidSetInput(_ input: Input?)
}
private var kInputOperationAssociatedValue = 0
extension InputOperation where Self: OperationSubclassing {
var input: Input? {
get {
return synchronized {
return AssociatedValue.get(object: self, key: &kInputOperationAssociatedValue)
}
}
set {
synchronized {
AssociatedValue.set(object: self, key: &kInputOperationAssociatedValue, value: newValue)
operationDidSetInput(newValue)
}
}
}
func operationDidSetInput(_ input: Input?) {
// Override in subclasses
}
}
extension InputOperation {
@discardableResult func inject<Dependency>(from dependency: Dependency, via block: @escaping (Dependency.Output) -> Input?) -> Self
where Dependency: OutputOperation
{
let observer = OperationBlockObserver<Dependency>(willFinish: { [weak self] (operation) in
guard let self = self else { return }
if let output = operation.output {
self.input = block(output)
}
})
dependency.addObserver(observer)
addDependency(dependency)
return self
}
@discardableResult func injectResult<Dependency>(from dependency: Dependency) -> Self
where Dependency: OutputOperation, Dependency.Output == Input?
{
return self.inject(from: dependency, via: { $0 })
}
/// Inject input from operation that outputs `Result<Input, Failure>`
@discardableResult func injectResult<Dependency, Failure>(from dependency: Dependency) -> Self
where Dependency: OutputOperation, Failure: Error, Dependency.Output == Result<Input, Failure>
{
return self.inject(from: dependency) { (output) -> Input? in
switch output {
case .success(let value):
return value
case .failure:
return nil
}
}
}
/// Inject input from operation that outputs `Result<Input, Never>`
@discardableResult func injectResult<Dependency>(from dependency: Dependency) -> Self
where Dependency: OutputOperation, Dependency.Output == Result<Input, Never>
{
return self.inject(from: dependency) { (output) -> Input? in
switch output {
case .success(let value):
return value
}
}
}
/// Inject input from operation that outputs `Result<Input?, Never>`
@discardableResult func injectResult<Dependency>(from dependency: Dependency) -> Self
where Dependency: OutputOperation, Dependency.Output == Result<Input?, Never>
{
return self.inject(from: dependency) { (output) -> Input? in
switch output {
case .success(let value):
return value
}
}
}
}
|