Search code examples
arraysswiftcombineflatmap

Merge two Combine Arrays into a Single Array


I have two types

let left: Future<[Int]>
let right: Future<[Int]>

How can I combine these so I have one contiguous 1D array?

Using append and merge create 2D arrays and there's no clear information. Is really the best way to collect the 2D arrays and then use a flatMap inside of a flatMap like:

.collect().flatMap { arrays in arrays.flatMap { $0 } }

there has to be a better way.


Solution

  • If you have two publishers emitting values that you want to combine somehow, you generally have two types of behavior that you might want: (1) zip - wait for each to emit, or (2) combineLatest - emit as soon as any one emits a value.

    So, in your case, it could be a zip

    left.zip(right)
        .map { (l, r) in l + r)
        .sink { ... }
    

    or a combineLatest:

    left.combineLatest(right)
        .map { (l, r) in l + r)
        .sink { ... }
    

    They behave the same, if both left and right emit a single value (e.g. like a Future does). So, if left emits [1,4] and right emits [2,3,5], the output would be [1,4,2,3,5]

    The difference is what happens after.

    With zip, when left emits the next value, say [11,44], there would be no output until right emits a value, say [22,33,55], and then the output would be: [11,44,22,33,55].

    With combineLatest, as soon as left emits, the output would be [11,44,2,3,5] and then when right emits, the output would be [11,44,22,33,55]