I’d like to be notified the moment all Combine publishers have done their work like DispatchGroup
and .notify
do.
For example, at the below codes, I want to show ProgressView
while publishers(pub1
, pub2
) doing their job.
import Combine
import Foundation
import SwiftUI
struct SwiftUIView: View {
@State var isFinished = false
let pub1 = ["one", "two", "three", "four"].publisher
let pub2 = ["five", "six", "seven", "eight"].publisher
var subscriptions = Set<AnyCancellable>()
var body: some View {
if isFinished {
Text("Hello, World!")
} else {
ProgressView()
}
}
init() {
pub1
.sink { print($0) }
.store(in: &subscriptions)
pub2
.sink { print($0) }
.store(in: &subscriptions)
// Where should I write this code?
// isFinished = true
}
}
My question is that how can I wait until publishers finish and show "Hello world" at the right time?
Is there anything I should know? If so, please let me know. Thank you!
2
Answers
A possible way is a view model. In this class
merge
the publishers and use thereceiveCompletion:
parameterYou can use the Zip operator. Zip operator only publishes after receiving events from all publishers. On the other hand, Merge will publish every time one of the publishers, publishes new value.