Operator
Concat requires the same data type
Indeed, the Concat operator allows you to execute a sequence of observables, but the problem you may encounter when using Concat is that the Concat operator requires that the Observable have the same general type.
let numbers : Observable<Int> = Observable.from([1,2,3]) let moreNumbers : Observable<Int> = Observable.from([4,5,6]) let names : Observable<String> = Observable.from(["Jose Rizal", "Leonor Rivera"]) // This works numbers.concat(moreNumbers) // Compile error numbers.concat(names)
The FlatMap operator allows you to group the sequence of Observable s
Here is an example.
class Tag { var tag: String = "" init (tag: String) { self.tag = tag } } let getRequestReadHTML : Observable<String> = Observable .just("<HTML><BODY>Hello world</BODY></HTML>") func getTagsFromHtml(htmlBody: String) -> Observable<Tag> { return Observable.create { obx in // do parsing on htmlBody as necessary obx.onNext(Tag(tag: "<HTML>")) obx.onNext(Tag(tag: "<BODY>")) obx.onNext(Tag(tag: "</BODY>")) obx.onNext(Tag(tag: "</HTML>")) obx.onCompleted() return Disposables.create() } } getRequestReadHTML .flatMap{ getTagsFromHtml(htmlBody: $0) } .subscribe (onNext: { e in print(e.tag) })
Note that getRequestReadHTML is of type Observable<String> , and the getTagsFromHtml function is of type Observable<Tag> .
Using multiple flat cards may increase the frequency of radiation
Be careful, as the flatMap operator accepts an array (for example, [1,2,3]) or a sequence (for example, observable) and will emit all elements as radiation. That is why it is known that the transformation 1...n was obtained.
If you define an observable, such as a network call, and you are sure that there will be only one radiation, you will not encounter any problems, since its conversion is 1...1 (i.e. one observation of one NSData ) Fine!
However, if your Observable has multiple outliers, be very careful because the chained flatMap operators will mean that outliers will increase exponentially (?).
A concrete example is when the first observable emits 3 emissions, the flatMap operator converts 1...n , where n = 2, which means that there are currently only 6 outliers. Another flatMap operator could again convert 1...n , where n = 2, which means there are currently only 12 outliers. Double check if this is your expected behavior.