From 0ac8b98bf711b533b20dd0593b383055d10fb1e0 Mon Sep 17 00:00:00 2001 From: Manish Rathi Date: Sat, 5 Aug 2023 13:52:23 +0200 Subject: [PATCH] OR-5269 Operators:: Sequence Operators:: Finding values:: `max(by:)` --- .../SequenceFindingValuesTests.swift | 37 +++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) diff --git a/CombineDemo/CombineDemoTests/Operators/SequenceOperators/SequenceFindingValuesTests.swift b/CombineDemo/CombineDemoTests/Operators/SequenceOperators/SequenceFindingValuesTests.swift index 53b9bd8..d487165 100644 --- a/CombineDemo/CombineDemoTests/Operators/SequenceOperators/SequenceFindingValuesTests.swift +++ b/CombineDemo/CombineDemoTests/Operators/SequenceOperators/SequenceFindingValuesTests.swift @@ -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! @@ -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 + + 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"]) + } } diff --git a/README.md b/README.md index 37f651c..6f382a1 100644 --- a/README.md +++ b/README.md @@ -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