Created
August 13, 2023 19:58
-
-
Save BrunoCerberus/cd9252dabf705c26d31f89ce58298e11 to your computer and use it in GitHub Desktop.
Zip Publishers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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