Last active
August 9, 2022 07:56
-
-
Save darthpelo/134ac483087be62160c3d11976254bc2 to your computer and use it in GitHub Desktop.
ViewModel, binding and generic
This file contains hidden or 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
// Ispired by http://rasic.info/bindings-generics-swift-and-mvvm/ | |
class Dynamic<T> { | |
typealias Listener = (T) -> Void | |
var listener: Listener? | |
func bind(listener: Listener?) { | |
self.listener = listener | |
} | |
func bindAndFire(listener: Listener?) { | |
self.listener = listener | |
listener?(value) | |
} | |
var value: T { | |
didSet { | |
listener?(value) | |
} | |
} | |
init(_ varible: T) { | |
value = varible | |
} | |
} | |
// Unit test | |
func testDynamicInt() { | |
let sut = Dynamic(3) | |
XCTAssertEqual(sut.value, 3) // ✅ | |
sut.bindAndFire { (value) in | |
XCTAssertEqual(value, 3) // ✅ | |
} | |
} | |
func testDynamicString() { | |
let sut = Dynamic("test_1") | |
XCTAssertEqual(sut.value, "test_1") // ✅ | |
sut.bind { (value) in | |
XCTAssertEqual(value, "t") // ❌ | |
} | |
} |
This file contains hidden or 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
import Foundation | |
import RxSwift | |
protocol GenericViewModel { | |
associatedtype T | |
var generic: T { get set } | |
func getValue() -> T | |
} | |
struct LoginViewModel: GenericViewModel { | |
typealias T = String | |
var generic: T { | |
didSet { | |
self.username.value = generic | |
} | |
} | |
private let username = Variable<T>("") | |
init(username: String) { | |
self.generic = username | |
} | |
func getValue() -> String { | |
return username.value | |
} | |
/// Temporary func to test Generic impelementation | |
/// | |
/// - Returns: The username String | |
func getUsername() -> String { | |
return username.value | |
} | |
} | |
// Unit Test | |
func testConstructur() { | |
var sut: LoginViewModel = LoginViewModel(username: "test_1") | |
XCTAssertEqual(sut.getUsername(), "test_1") // ❌ | |
XCTAssertEqual(sut.generic, "test_1") // ✅ | |
sut.generic = "test_2" | |
XCTAssertEqual(sut.getUsername(), "test_2") // ✅ | |
XCTAssertEqual(sut.getValue(), "test_2") // ✅ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment