Github.com/agelessman/…

The core idea of Matching Datas is to determine whether the output data of a pipline matches a certain condition.

allSatisfy

As shown in the figure above, allSatisfy accepts as a parameter a closure whose return value is of type bool. Pipline will only print true if all output from Publisher causes the closure to return true.

It’s worth noting that,allSatisfyIs blocking publisher and must wait for publisher to finish sending.finishedData is output after the event. This indicates that the timing of allSatisfy calculation results is after publisher sends them.finishedEvents.

Let’s look at another schematic that returns false:

The code is as follows:

cancellables = Set<AnyCancellable> ()let publisher = PassthroughSubject<String.Never>()

  publisher
      .allSatisfy { value in
          value.count > 2
      }
      .sink { print($0) }
      .store(in: &cancellables)

  publisher.send("abc")
  publisher.send("defg")
  publisher.send("hijklmn")
Copy the code

An extension of allSatisfy is tryAllSatisfy, which allows a closure to throw an exception and is not explained here.

contains

As can be seen from the figure above,. Contains can be used very simply:

  • Determine whether the output data from Publisher meets the criteria
  • As soon as the qualified data is found, terminate the Pipline and return true
  • If publisher sends.finishedIf no matching data is found, false is returned

It’s important to note that once contains meets this condition it immediately terminates the pipline,.contains(2)Is the default, but it requires the output from Publisher to implement the Equatable protocol, which is the only way to determine if two values are equal.

cancellables = Set<AnyCancellable> () [1.2.3]
    .publisher
    .contains(2)
    .sink { print($0) }
    .store(in: &cancellables)
Copy the code

Contains (Where predicate:) can be used without implementing the Equatable protocol, as shown in the following figure:

And you can see that the result is exactly the same as dot contains(2) except for the closure, and that’s the great advantage of declarative programming, because you can define a closure, which is like a specification.

[1.2.3]
    .publisher
    .contains { value -> Bool in
        value = = 2
    }
    .sink { print($0) }
    .store(in: &cancellables)
Copy the code

Of course, there’s always an extension of try,. Contains(where predicate:), which allows exceptions to be thrown from the closure, which I won’t explain here.