Last active
February 17, 2024 02:21
-
-
Save LarsStegman/c9d71ab7f3d0967a8927c977c995cfd3 to your computer and use it in GitHub Desktop.
In the second beta of the Swift framework Combine there was no easy way to split a publisher output of type Sequence into separate values for every element in the sequence. This extension to Publisher adds an operator to do this.
This file contains 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 | |
extension Publisher where Output: Sequence { | |
func sequence() -> Publishers.FlatMap<Publishers.Sequence<Self.Output, Self.Failure>, Self> { | |
self.flatMap { Publishers.Sequence(sequence: $0) } | |
} | |
} | |
let publisher = PassthroughSubject<Array<Int>, Never>() | |
publisher | |
.sink { | |
print($0) | |
} | |
publisher.send([1, 2, 3, 4, 5]) | |
publisher.send([1, 2, 3, 4, 5]) | |
// Prints: | |
// [1, 2, 3, 4, 5] | |
// [1, 2, 3, 4, 5] | |
let publisher2 = PassthroughSubject<Array<Int>, Never>() | |
publisher2 | |
.sequence() | |
.sink { | |
print($0) | |
} | |
publisher2.send([1, 2, 3, 4, 5]) | |
publisher2.send([1, 2, 3, 4, 5]) | |
// Prints: | |
// 1 | |
// 2 | |
// 3 | |
// 4 | |
// 5 | |
// 1 | |
// 2 | |
// 3 | |
// 4 | |
// 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment