CombineCommunity / rxswift-to-combine-cheatsheet

RxSwift to Apple’s Combine Cheat Sheet
https://medium.com/gett-engineering/rxswift-to-apples-combine-cheat-sheet-e9ce32b14c5b
MIT License
2.04k stars 125 forks source link

merge(maxConcurrent:) vs flatMap(maxPublishers:) #19

Closed klop closed 3 years ago

klop commented 4 years ago
import RxSwift

var values: [Int] = []

var inputSubject = PublishSubject<Observable<Int>>()

let disposable = inputSubject
  .merge(maxConcurrent: 2)
  .subscribe(onNext: { values.append($0) })

let a = PublishSubject<Int>()
let b = PublishSubject<Int>()

inputSubject.onNext(a)
inputSubject.onNext(b)
inputSubject.onNext(.just(3))

a.onNext(1)

values // [1]

b.onNext(2)

values // [1, 2]

b.onCompleted()

values // [1, 2, 3]
import Combine

var values: [Int] = []

var inputSubject = PassthroughSubject<AnyPublisher<Int, Never>, Never>()

let cancellable = inputSubject
  .flatMap(maxPublishers: .max(2), { $0 })
  .sink { values.append($0) }

let a = PassthroughSubject<Int, Never>()
let b = PassthroughSubject<Int, Never>()

inputSubject.send(a.eraseToAnyPublisher())
inputSubject.send(b.eraseToAnyPublisher())
inputSubject.send(Just(3).eraseToAnyPublisher())

a.send(1)

values // [1]

b.send(2)

values // [1, 2]

b.send(completion: .finished)

values // [1, 2] (seems like Just(3) was dropped)

Unless I'm mistaken, the cheat sheet should be updated to reflect this difference.

freak4pc commented 4 years ago

It could be that there's a variation in the implementation for some reason, but unfortunately we can't see what's going on inside Combine. They are parallel in the conceptual sense.

Regardless, I'm happy to accept a PR to modify the description a bit if you see fit.

Thanks @klop !