Skip to content
This repository has been archived by the owner on Jan 24, 2023. It is now read-only.

Commit

Permalink
Merge pull request #99 from UrbanCompass/map-void
Browse files Browse the repository at this point in the history
separate map on variable and unique
  • Loading branch information
wesbillman authored Sep 4, 2018
2 parents 01157aa + 2d2b156 commit 81d3eb8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
6 changes: 6 additions & 0 deletions Snail/Unique.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,10 @@ public class Unique<T: Equatable>: Variable<T> {
super.init(value)
subject.on(.next(value))
}

public override func map<U>(transform: @escaping (T) -> U) -> Unique<U> {
let newVariable = Unique<U>(transform(value))
asObservable().subscribe(onNext: { _ in newVariable.value = transform(self.value) })
return newVariable
}
}
4 changes: 2 additions & 2 deletions Snail/Variable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ public class Variable<T> {
return subject
}

public func map<U>(transform: @escaping (T) -> U) -> Unique<U> {
let newVariable = Unique<U>(transform(value))
public func map<U>(transform: @escaping (T) -> U) -> Variable<U> {
let newVariable = Variable<U>(transform(value))
asObservable().subscribe(onNext: { _ in newVariable.value = transform(self.value) })
return newVariable
}
Expand Down
37 changes: 37 additions & 0 deletions SnailTests/VariableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 81d3eb8

Please sign in to comment.