Created
August 13, 2023 19:55
-
-
Save BrunoCerberus/ecc416dac7bee74d03589565ce596f7a to your computer and use it in GitHub Desktop.
CombineLatest of 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 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