Created
August 13, 2023 20:14
-
-
Save BrunoCerberus/6991d5e19347d0b02e9a4975aa98a14d to your computer and use it in GitHub Desktop.
Merge Publisher
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, 10].publisher | |
// Create a publisher from an array of odd integers. | |
let oddIntegersPublisher = [1, 3, 5, 7, 9].publisher | |
// Use the `Merge` operator to combine the emissions of the even and odd integer publishers | |
// into a single stream of values. | |
// This means that as each publisher emits a value, the merged stream will emit that value, | |
// effectively interweaving the two sequences of numbers. | |
Publishers.Merge( | |
evenIntegersPublisher, | |
oddIntegersPublisher | |
) | |
.sink { value in | |
// For every value emitted from the merged stream (be it even or odd), print it out. | |
print(value) | |
} | |
// Store the subscription in the `cancellables` set. | |
// This ensures that the subscription remains active and won't be prematurely deallocated. | |
.store(in: &cancellables) | |
//2 | |
//4 | |
//6 | |
//8 | |
//10 | |
//1 | |
//3 | |
//5 | |
//7 | |
//9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment