Skip to content

Instantly share code, notes, and snippets.

@pofat
Created Jan 12, 2022
Embed
What would you like to do?
[Effect<Output, Failure>] -> Effect<[Output], Failure>
extension Effect {
// Zip with other effects
func zip<Others: Collection>(with others: Others)
-> Effect<[Output], Failure>
where Others.Element == Effect<Output, Failure> {
let first = map { [$0] }
.eraseToEffect()
return others
.reduce(first) { zipped, next in
zipped
.zip(next)
.map { $0.0 + [$0.1] }
.eraseToEffect()
}
.eraseToEffect()
}
}
// Use this for effect array
func zip<Output, Failure: Error>(_ effects: [Effect<Output, Failure>]) -> Effect<[Output], Failure> {
switch effects.count {
case 0:
return .none
case 1:
return effects[effects.startIndex].zip(with: [Effect<Output, Failure>]())
default:
let first = effects[effects.startIndex]
let others = effects[effects.index(after: effects.startIndex)...]
return first.zip(with: others)
}
}
// Usage
let first = Effect<Int, Never>(value: 1)
let second = Effect<Int, Never>(value: 2)
let third = Effect<Int, Never>(value: 3)
let forth = Effect<Int, Never>(value: 4)
let zipped = zip([first, second, third, forth]) // Effect<[Int], Never>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment