user3569109
user3569109

Reputation: 191

How can I convert an element to an array?

The array was converted to Observable using the from operator as shown below.

Observable.from([1, 2, 3, 4, 5])
  .subscribe(onNext: {
    print($0)
  })
  .disposed(by: disposeBag)
//Result Value
1
2
3
4
5

After that, I want to use several map or flatMap operators to transform, and finally I want to make an array again.
Is there an Rx operator that can create an array without using toArray()?

Observable.from([1, 2, 3, 4, 5])
  .map { .... }
  .flatMap { .... }
  .map { .... }
  ????? -> convert to Array
  .subscribe(onNext: {
    print($0)
  })
  .disposed(by: disposeBag)
//Expected Value
[someItem1, someItem2, ..., someItem5]

Upvotes: 0

Views: 127

Answers (1)

Daniel T.
Daniel T.

Reputation: 33979

No, the toArray operator is exactly what you want given that you have used Observable.from. That said, you don't need to break the array up in the first place.

Also, the way you have things now, the return order is not guaranteed. If the various operations in the flatMap return at different times, the resulting array will be in a different order than the source.

If you don't break the array up with from then you won't need to recombine it later with toArray and you won't have the ordering issues.

Observable.just([1, 2, 3, 4, 5])
    .map { $0.map { /* transform each value */ } }
    .flatMap { Observable.zip($0.map { /* create an Observable using each value */ }) }
    .map { $0.map { /* transform each value */ } }
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

Upvotes: 1

Related Questions