Skip to content

Commit

Permalink
OR-5269 Operators:: Sequence Operators:: Finding values:: max(by:) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
crazymanish authored Aug 5, 2023
1 parent 5c11196 commit e88f35d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import XCTest
- `max()` Publishes the maximum value received from the upstream publisher, after it finishes.
- https://developer.apple.com/documentation/combine/publishers/reduce/max()
- `max(by:)` Publishes the maximum value received from the upstream publisher, using the provided ordering closure.
- A closure that receives two elements and returns true if they’re in increasing order.
- https://developer.apple.com/documentation/combine/publishers/reduce/max(by:)
*/
final class SequenceFindingValuesTests: XCTestCase {
var cancellables: Set<AnyCancellable>!
Expand Down Expand Up @@ -124,4 +128,37 @@ final class SequenceFindingValuesTests: XCTestCase {
XCTAssertTrue(isFinishedCalled)
XCTAssertEqual(receivedValues, [10])
}

func testPublisherWithMaxByOperator() {
// Given: Publisher
let publisher = [
"12345",
"ab",
"hello world"
]
.compactMap { $0.data(using: .utf8) } // [Data]
.publisher // Publisher<Data, Never>

var receivedValues: [String] = []

// When: Sink(Subscription)
// Data doesn't conform to Comparable, that's why using the max(by:) operator to find the Data-object with the largest number of bytes.
// The publisher emits all its Data objects and finishes, then max(by:) finds and emits the data with the largest byte size and sink receives it.
publisher
.max(by: { $0.count < $1.count }) // Returns the maximum value (based on Data-bytes count), after upstream will finish!
.sink { [weak self] completion in
switch completion {
case .finished:
self?.isFinishedCalled = true
}
} receiveValue: { value in
let stringValue = String(data: value, encoding: .utf8)!
receivedValues.append(stringValue)
}
.store(in: &cancellables)

// Then: Receiving correct value
XCTAssertTrue(isFinishedCalled)
XCTAssertEqual(receivedValues, ["hello world"])
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
- `min()` https://github.com/crazymanish/what-matters-most/pull/110
- `min(by:)` https://github.com/crazymanish/what-matters-most/pull/111
- `max()` https://github.com/crazymanish/what-matters-most/pull/112
- `max(by:)` https://github.com/crazymanish/what-matters-most/pull/113
- [ ] Query the publisher
- [ ] Practices

Expand Down

0 comments on commit e88f35d

Please sign in to comment.