Created
November 4, 2019 03:43
-
-
Save fmo91/f4eb10d83502f24c4b98f21ab3fbff34 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class ViewModel { | |
// 1. | |
@Published var operation: MathOperation? | |
@Published var operationText: String? | |
@Published var firstNumberText: String? | |
@Published var secondNumberText: String? | |
@Published var result: String? | |
@Published private var firstNumber: Int? | |
@Published private var secondNumber: Int? | |
// 2. | |
private var cancellables: [AnyCancellable] = [] | |
init() { | |
// 3. | |
$firstNumberText | |
.compactMap({ Int($0 ?? "") }) | |
.assign(to: \.firstNumber, on: self) | |
.add(to: &cancellables) | |
$secondNumberText | |
.compactMap({ Int($0 ?? "") }) | |
.assign(to: \.secondNumber, on: self) | |
.add(to: &cancellables) | |
$operation | |
.compactMap({ $0?.rawValue }) | |
.assign(to: \.operationText, on: self) | |
.add(to: &cancellables) | |
// 4. | |
Publishers.CombineLatest3($firstNumber, $secondNumber, $operation) | |
.tryMap { (firstNumber: Int?, secondNumber: Int?, operation: MathOperation?) throws -> String? in | |
guard | |
let firstNumber = firstNumber, | |
let secondNumber = secondNumber, | |
let operation = operation | |
else { | |
return nil | |
} | |
let result = try operation.operate(on: firstNumber, and: secondNumber) | |
return result.description | |
} | |
.catch { (error: Error) -> Just<String?> in | |
switch error { | |
case MathOperation.Error.divideByZero: | |
return Just("Cannot divide by zero") | |
default: | |
return Just("Something went wrong...") | |
} | |
} | |
.assign(to: \.result, on: self) | |
.add(to: &cancellables) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment