Skip to content

Instantly share code, notes, and snippets.

@BrunoCerberus
Created August 13, 2023 19:58
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/cd9252dabf705c26d31f89ce58298e11 to your computer and use it in GitHub Desktop.
Save BrunoCerberus/cd9252dabf705c26d31f89ce58298e11 to your computer and use it in GitHub Desktop.
Zip Publishers
import Combine
// A set to store any active Combine subscriptions (cancellables).
// This is essential for ensuring that the 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 `Zip` operator to combine values from the even and odd integer publishers
// based on their positions in their respective sequences.
// For example, the first item from `evenIntegersPublisher` will be combined with the first
// item from `oddIntegersPublisher`, the second with the second, and so on.
Publishers.Zip(
evenIntegersPublisher,
oddIntegersPublisher
)
.sink { even, odd in
// For every paired 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 2 and latest odd is 1
//Latest even is 4 and latest odd is 3
//Latest even is 6 and latest odd is 5
//Latest even is 8 and latest odd is 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment