Hello!
I noticed a behavioral difference between first()
and prefix(1)
and I'm not sure why this happens - I might just not understand something here.
I'm basically doing a flatMapLatest
with a side-effect (don't judge, i'm experimenting)
import Combine
let sourceSubject = CurrentValueSubject<Int, Never>(1)
let targetPublisher = Just("Hello").delay(for: .seconds(3), scheduler: RunLoop.main)
let subscription = sourceSubject
.removeDuplicates()
.prefix(1) // .first()
.handleEvents(
receiveSubscription: { print("source receive subscription \($0)") },
receiveOutput: { print("source receive output \($0)") },
receiveCompletion: { print("source receive completion \($0)") },
receiveCancel: { print("source receive cancel") },
receiveRequest: { print("source receive request \($0)") }
)
.map { _ in
targetPublisher
}
// Side effect, without it everything behaves the same
.handleEvents(receiveOutput: { _ in
sourceSubject.value = 2
})
.switchToLatest()
.handleEvents(
receiveSubscription: { print("target receive subscription \($0)") },
receiveOutput: { print("target receive output \($0)") },
receiveCompletion: { print("target receive completion \($0)") },
receiveCancel: { print("target receive cancel") },
receiveRequest: { print("target receive request \($0)") }
)
.sink {
print("Sink value: \($0)")
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
subscription.cancel()
}
While with first()
everything behaves as I expected:
target receive subscription SwitchToLatest
target receive request unlimited
source receive subscription First
source receive request unlimited
source receive output 1
Send new subject value
source receive completion finished
target receive output Hello
Sink value: Hello
target receive completion finished
with prefix(1)
, the resulting publisher completes immediately:
target receive subscription SwitchToLatest
target receive request unlimited
source receive subscription Output
source receive request unlimited
source receive output 1
Send new subject value
source receive completion finished
target receive completion finished
Is this expected? If so, does anyone know the root reason?
Thanks a lot