RxSwift_v1.0笔记——7 Transforming Operators

Transforming elements

toArray

将sequence转换成一个array,并转换成单一事件信号,然后结束

RxSwift_v1.0笔记——7 Transforming Operators_第1张图片
example(of: "toArray") {
  let disposeBag = DisposeBag()
  // 1
  Observable.of("A", "B", "C")
    // 2
    .toArray()
    .subscribe(onNext: {
      print($0)
    })
    .addDisposableTo(disposeBag)
}
--- Example of: toArray ---
["A", "B", "C"]

map

通过传入一个函数闭包把原来的sequence转变为一个新的sequence的操作

RxSwift_v1.0笔记——7 Transforming Operators_第2张图片
example(of: "map") {
  let disposeBag = DisposeBag()
  // 1
  let formatter = NumberFormatter()
  formatter.numberStyle = .spellOut

  // 2
  Observable.of(123, 4, 56)
    // 3
    .map {
      formatter.string(from: $0) ?? ""
    }
    .subscribe(onNext: {
      print($0)
    })
    .addDisposableTo(disposeBag)
}
--- Example of: map ---
one hundred twenty-three
four
fifty-six

mapWithInde

同map函数,就是多加了个index

RxSwift_v1.0笔记——7 Transforming Operators_第3张图片
example(of: "mapWithIndex") {

  let disposeBag = DisposeBag()

  // 1
  Observable.of(1, 2, 3, 4, 5, 6)
    // 2
    .mapWithIndex { integer, index in
      index > 2 ? integer * 2 : integer
    }
    .subscribe(onNext: {
      print($0)
    })
    .addDisposableTo(disposeBag)
}
--- Example of: mapWithIndex ---
1
2
3
8
10
12

Transforming inner observables

flatMap

将多个sequence转换为一个sequences,当你接收一个sequence的事件,你还想接收其他sequence发出的事件的话可以使用flatMap,她会将每一个sequence事件进行处理以后,然后再以一个新的sequence形式发出事件。和Swift中的意思差不多。flatMap只能用在subject中


RxSwift_v1.0笔记——7 Transforming Operators_第4张图片
struct Student {

  var score: Variable

}

example(of: "flatMap") {
  let disposeBag = DisposeBag()
  // 1
  let ryan = Student(score: Variable(80))
  let charlotte = Student(score: Variable(90))
  // 2
  let student = PublishSubject()
  // 3
  student.asObservable()
    .flatMap {
      $0.score.asObservable()
    }
    // 4
    .subscribe(onNext: {
      print($0)
    })
    .addDisposableTo(disposeBag)
  student.onNext(ryan)
  ryan.score.value = 85

  student.onNext(charlotte)
  ryan.score.value = 95

  charlotte.score.value = 100
}
--- Example of: flatMap ---
80
85
90
95
100

flatMapLatest

只会接收最新序列的事件

RxSwift_v1.0笔记——7 Transforming Operators_第5张图片
example(of: "flatMapLatest") {

  let disposeBag = DisposeBag()

  let ryan = Student(score: Variable(80))
  let charlotte = Student(score: Variable(90))

  let student = PublishSubject()

  student.asObservable()
    .flatMapLatest {
      $0.score.asObservable()
    }
    .subscribe(onNext: {
      print($0)
    })
    .addDisposableTo(disposeBag)

  student.onNext(ryan)

  ryan.score.value = 85

  student.onNext(charlotte)

  // 1
  ryan.score.value = 95

  charlotte.score.value = 100
}
--- Example of: flatMapLatest ---
80
85
90
100

你可能感兴趣的:(RxSwift_v1.0笔记——7 Transforming Operators)