4

We know Empty Publisher in Combine will trigger a completion event immediately:

Empty<Void,Never>()
 .sink {
 print("completion: \(0ドル)") // will print!
 } receiveValue: {}

But Empty Publisher that flatMap returned will NOT trigger completion event:

var subs = Set<AnyCancellable>()
let p0 = PassthroughSubject<[Int],Error>()
let p1 = p0
 .flatMap {_ in
 Empty<Void,Never>() // same Empty Publisher
 }.eraseToAnyPublisher()
p1
 .sink {
 print("completion: \(0ドル)") // but NOT print!
 } receiveValue: {}
 .store(in: &subs)
p0.send([1,2,3])

Why is that??? Am I miss something??? Thanks! ;)

asked May 5, 2021 at 0:51
2
  • You seem to have misunderstood the semantics of flatMap. p0.flatMap(f) gives you a publisher that, for each element x that p0 publishes, instead of publishing x, it publishes what the publisher f(x) would publish. When will p0.flatMap(f) complete publishing? Clearly, that doesn't depend on f(x) - it depends on p0. Commented May 5, 2021 at 0:59
  • What exactly are you trying to achieve with your code? Do you want the upstream publisher to stop once some condition is met or something like that? Commented May 5, 2021 at 1:00

1 Answer 1

5

FlatMap works in the following way: for every upstream value it creates a publisher. The downstream receives all the values emitted by all these FlatMap-created publishers.

It completes when the upstream completes, or errors out if either the upstream errors out, or if any created publishers error out.

So, in your case, for the single upstream value of [1,2,3] you emit an Empty publisher (which completes), but there's no overall completion because PassthroughSubject hasn't completed.

p0.send([1,2,3])
p0.send(completion: .finished)

The above would complete the entire pipeline.

answered May 5, 2021 at 1:03
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.