- Use concat. merge doesn’t make the elements in order.
return .concat(
getInitialData(),
expandPositionIfCountIsOne()
)
2. But if codes like this, it doesn’t work
private func expandPositionIfCountIsOne() -> Observable<Mutation> {
if currentState.positions?.count == 1,
let userStock = currentState.positions?.first {
return expandPosition(userStock: userStock)
}
return .empty()
}
Because the condition line executes right after, not in observable not after getInitialData. So it always return empty()
3. So the codes need to be like this
private func expandPositionIfCountIsOne() -> Observable<Mutation> {
return Observable<Void>.just(())
.observe(on: MainScheduler.instance)
.flatMap { [weak self] _ in
guard let self = self,
self.currentState.positions?.count == 1,
let userStock = self.currentState.positions?.first
else {
return Observable<Mutation>.empty()
}
return self.expandPosition(userStock: userStock)
}
}
Chain the condition inside the observable. Because it reads currentState, it’s better to use MainScheduler.instance
4. What if just call the repository data without chaining into the observable
positionRepository.getUserStock(stockID: stockID, positionID: positionID)
.map { Mutation.setUserStockDetail(positionID, $0) }
.catch { error in
Toast.somethingWentWrong(error: error)
}
This doesn’t do anything. Because the result is not observed.
5. Map -> Mutation, flatMap -> Observable
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) throws -> Result)
-> Single<Result> {
return Single(raw: self.primitiveSequence.source.map(transform))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Result>(_ selector: @escaping (Element) throws -> Single<Result>)
-> Single<Result> {
return Single<Result>(raw: self.primitiveSequence.source.flatMap(selector))
}