Each time I think I have an understanding about the flatMap
operator I come to some issue that make me feel I don't understand nothing .
The example I'm going to post don't make any sense is just to show the issue and I'm not looking to achieve nothing in that way, just trying to understand why is this happening.
Take this snippet as example:
let cvsOne = CurrentValueSubject<String, Never>("Kitty")
let canc = ["Small","Warm"].publisher
.handleEvents(receiveSubscription: { (sub) in
print("Step 1 Received sub \(sub)")
}, receiveOutput: { (value) in
print("Step 1 Received output \(value)")
}, receiveCompletion: { (completion) in
print("Step 1 Received completion \(completion)")
}, receiveCancel: {
print("Step 1 Received cancel")
}, receiveRequest: { (req) in
print("Step 1 Received request \(req)")
})
.flatMap { (val) in
return cvsOne
}
.handleEvents(receiveSubscription: { (sub) in
print("Step 2 Received sub \(sub)")
}, receiveOutput: { (value) in
print("Step 2 Received output \(value)")
}, receiveCompletion: { (completion) in
print("Step 2 Received completion \(completion)")
}, receiveCancel: {
print("Step 2 Received cancel")
}, receiveRequest: { (req) in
print("Step 2 Received request \(req)")
})
.sink { (value) in
print("Sink Received \(value)")
}
Here is the output of the console, as I expected the sink is called 2 times.
Step 2 Received request unlimited
Step 2 Received sub FlatMap
Step 1 Received request unlimited
Step 1 Received sub ["Small", "Warm"]
Step 1 Received output Small
Step 2 Received output Kitty
Sink Received Kitty
Step 1 Received output Warm
Step 2 Received output Kitty
Sink Received Kitty
Step 1 Received completion finished
Taking the same code this is what happen if, after the first execution, I send
cvsTwo.send("Little ball")
The sink is executed 2 more times, I would have expect just one.
Sending more data
Step 2 Received output Little ball
Sink Received Little ball
Step 2 Received output Little ball
Sink Received Little ball
I really can't figure out why is this happening, it seems that the subscriber is subscribed the same number of times as the count of the array published. Of course if I increment the number of elements in the array it will grow accordingly.
Is there someone that could explain me this behaviour?