Skip to content

Instantly share code, notes, and snippets.

@BrunoCerberus
Created August 13, 2023 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrunoCerberus/ecc416dac7bee74d03589565ce596f7a to your computer and use it in GitHub Desktop.
Save BrunoCerberus/ecc416dac7bee74d03589565ce596f7a to your computer and use it in GitHub Desktop.
CombineLatest of Publishers
import Combine
// A set to store any active Combine subscriptions (cancellables).
// This ensures that subscriptions are kept alive and not deallocated prematurely.
var cancellables = Set<AnyCancellable>()
// Create a publisher from an array of even integers.
let evenIntegersPublisher = [2, 4, 6, 8].publisher
// Create a publisher from an array of odd integers.
let oddIntegersPublisher = [1, 3, 5, 7, 9].publisher
// Use the `CombineLatest` operator to combine the latest values
// from the even and odd integer publishers.
// This will emit a tuple of values every time one of the publishers emits a value,
// taking the latest value from each publisher.
Publishers.CombineLatest(
evenIntegersPublisher,
oddIntegersPublisher
)
.sink { even, odd in
// For every combined pair of even and odd integers, print them out.
print("Latest even is ", even, " and latest odd is ", odd)
}
// Store the subscription in the `cancellables` set.
// This ensures that the subscription remains active and won't be prematurely deallocated.
.store(in: &cancellables)
//Latest even is 10 and latest odd is 1
//Latest even is 10 and latest odd is 3
//Latest even is 10 and latest odd is 5
//Latest even is 10 and latest odd is 7
//Latest even is 10 and latest odd is 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment