diff --git a/Snail/Unique.swift b/Snail/Unique.swift index 37d82f0..9e4b19b 100644 --- a/Snail/Unique.swift +++ b/Snail/Unique.swift @@ -22,4 +22,10 @@ public class Unique: Variable { super.init(value) subject.on(.next(value)) } + + public override func map(transform: @escaping (T) -> U) -> Unique { + let newVariable = Unique(transform(value)) + asObservable().subscribe(onNext: { _ in newVariable.value = transform(self.value) }) + return newVariable + } } diff --git a/Snail/Variable.swift b/Snail/Variable.swift index 56376c3..57bb92e 100644 --- a/Snail/Variable.swift +++ b/Snail/Variable.swift @@ -31,8 +31,8 @@ public class Variable { return subject } - public func map(transform: @escaping (T) -> U) -> Unique { - let newVariable = Unique(transform(value)) + public func map(transform: @escaping (T) -> U) -> Variable { + let newVariable = Variable(transform(value)) asObservable().subscribe(onNext: { _ in newVariable.value = transform(self.value) }) return newVariable } diff --git a/SnailTests/VariableTests.swift b/SnailTests/VariableTests.swift index 7530d9d..d6c596a 100644 --- a/SnailTests/VariableTests.swift +++ b/SnailTests/VariableTests.swift @@ -64,4 +64,41 @@ class VariableTests: XCTestCase { XCTAssertEqual(subject.value.count, subjectCharactersCount) } + + func testUniqueFireCounts() { + let subject = Unique("one") + var firedCount = 0 + + subject.map { $0.count }.asObservable().subscribe(onNext: { _ in + firedCount += 1 + }) + + subject.value = "two" + + XCTAssertTrue(firedCount == 1) + } + + func testVariableFireCounts() { + let subject = Variable("one") + var firedCount = 0 + + subject.map { $0.count }.asObservable().subscribe(onNext: { _ in + firedCount += 1 + }) + + subject.value = "two" + + XCTAssertTrue(firedCount == 2) + } + + func testMapToVoid() { + let subject = Variable("initial") + var fired = false + + subject.map { _ in return () }.asObservable().subscribe(onNext: { _ in + fired = true + }) + + XCTAssertTrue(fired) + } }