Skip to content

Commit

Permalink
Add mapToVoid operator (CombineCommunity#129)
Browse files Browse the repository at this point in the history
  • Loading branch information
danshevluk authored Jul 23, 2022
1 parent 1c05161 commit 5c17b57
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Sources/Operators/MapToValue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,12 @@ public extension Publisher {
func mapToValue<Value>(_ value: Value) -> Publishers.Map<Self, Value> {
map { _ in value }
}

/// Replace each upstream value with Void.
///
/// - Returns: A new publisher wrapping the upstream and replacing each element with Void.
func mapToVoid() -> Publishers.Map<Self, Void> {
map { _ in () }
}
}
#endif
49 changes: 49 additions & 0 deletions Tests/MapToValueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,54 @@ final class MapToValueTests: XCTestCase {
barSubject.send(6)
XCTAssertEqual(result, "30")
}

func testMapToVoidWithMultipleEvents() {
let expectation = XCTestExpectation()
expectation.expectedFulfillmentCount = 3

let subject = PassthroughSubject<String, Never>()
subscription = subject
.mapToVoid()
.sink { element in
XCTAssertTrue(type(of: element) == Void.self)
expectation.fulfill()
}

subject.send("test 1")
subject.send("test 2")
subject.send("test 3")

wait(for: [expectation], timeout: 3)
}

func testMapToVoidWithError() {
let expectation = XCTestExpectation()
expectation.expectedFulfillmentCount = 3

enum TestError: Error {
case example
}

let subject = PassthroughSubject<String, Error>()
subscription = subject
.mapToVoid()
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
XCTFail()
default:
break
}
}, receiveValue: {
expectation.fulfill()
})

subject.send("test 1")
subject.send("test 2")
subject.send("test 3")
subject.send(completion: .failure(TestError.example))

wait(for: [expectation], timeout: 3)
}
}
#endif

0 comments on commit 5c17b57

Please sign in to comment.