Scott H
Scott H

Reputation: 1529

RxSwift operator for transforming Observable<[T]> to Observable<T> by taking first element

Currently I do something like this:

Observable.just([1, 2, 3, 4])
  .flatMapLatest {
    numbers in
    guard number = numbers.first else {
      return Objservable.empty()
    }
    return Observable.just(number)
  }

Is there a more idiomatic way to do this or any prebuilt operators I can use?

Upvotes: 1

Views: 776

Answers (2)

marcinax
marcinax

Reputation: 1195

Your solution is quite good, you can eg. move it into extension and it'll be more general. But if you really want to do this other way: you can take a look at RxOptionals and use it like:

Observable.just([1, 2, 3, 4])
        .filterEmpty()
        .map { $0.first }
        .filterNil()

Upvotes: 1

tomahh
tomahh

Reputation: 13661

The way you implemented it is absolutely correct. I'd simply have used flatMap in place of flatMapLatest as it is a more general operator and we don't need the special logic of flatMapLatest.

You could create your own operator that applies to observables that are of type Collection.

extension Observable where Element : Collection {
  func mapFirst() -> Observable<Element.Iterator.Element> {
    return self.flatMap { elements in
      guard number = numbers.first else {
        return Objservable.empty()
      }
      return Observable.just(number)
    }
  }
}

Upvotes: 2

Related Questions