RxSwift_v1.0笔记——9: Combining Operators

Prefixing and concatenating

startWith

增加前缀。在发出事件消息之前,先发出某个特定的事件消息。


RxSwift_v1.0笔记——9: Combining Operators_第1张图片
startWith
example(of: "startWith") {
  // 1
  let numbers = Observable.of(2, 3, 4)

  // 2
  let observable = numbers.startWith(1)
  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: startWith ---
1
2
3
4

concat

会把多个sequence和并为一个sequence,并且当前面一个sequence发出了completed事件,才会开始下一个sequence的事件。在第一sequence完成之前,第二个sequence发出的事件都会被忽略,但会接收一完成之前的二发出的最后一个事件。
下例中Observable直接完成了,所以相当于直接链接

RxSwift_v1.0笔记——9: Combining Operators_第2张图片
Observable.concat

example(of: "Observable.concat") {
  // 1
  let first = Observable.of(1, 2, 3)
  let second = Observable.of(4, 5, 6)

  // 2
  let observable = Observable.concat([first, second])

  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: Observable.concat ---
1
2
3
4
5
6

concat(_:)

an instance method of Observable, instead of a class method

example(of: "concat") {
  let germanCities = Observable.of("Berlin", "Munich", "Frankfurt")
  let spanishCities = Observable.of("Madrid", "Barcelona", "Valencia")

  let observable = germanCities.concat(spanishCities)
  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: concat ---
Berlin
Munich
Frankfurt
Madrid
Barcelona
Valencia

concat one element

同startWith(_:)

example(of: "concat one element") {
  let numbers = Observable.of(2, 3, 4)

  let observable = Observable
    .just(1)
    .concat(numbers)

  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: concat one element ---
1
2
3
4

Merging

merge

合并两个Observable流合成单个Observable流,根据时间轴发出对应的事件


RxSwift_v1.0笔记——9: Combining Operators_第3张图片
merge
example(of: "merge") {
  // 1
  let left = PublishSubject()
  let right = PublishSubject()

  // 2
  let source = Observable.of(left.asObservable(), right.asObservable())

  // 3
  let observable = source.merge()
  let disposable = observable.subscribe(onNext: { value in
    print(value)
  })

  // 4
  var leftValues = ["Berlin", "Munich", "Frankfurt"]
  var rightValues = ["Madrid", "Barcelona", "Valencia"]

  repeat {
    if arc4random_uniform(2) == 0 {
      if !leftValues.isEmpty {
        left.onNext("Left:  " + leftValues.removeFirst())
      }
    } else if !rightValues.isEmpty {
      right.onNext("Right: " + rightValues.removeFirst())
    }
  } while !leftValues.isEmpty || !rightValues.isEmpty

  // 5
  disposable.dispose()
}
--- Example of: merge ---
Left:  Berlin
Right: Madrid
Left:  Munich
Right: Barcelona
Left:  Frankfurt
Right: Valencia

combineLatest

绑定超过最多不超过8个的Observable流,结合在一起处理。和Zip不同的是combineLatest是一个流的事件对应另一个流的最新的事件,两个事件都会是最新的事件
Every time one of the inner (combined) sequences emits a value, it calls a closure you provide. You receive the last value from each of the inner sequences.


RxSwift_v1.0笔记——9: Combining Operators_第4张图片
combineLatest
example(of: "combineLatest") {
  let left = PublishSubject()
  let right = PublishSubject()

  // 1
  let observable = Observable.combineLatest(left, right, resultSelector: {
    lastLeft, lastRight in
    "\(lastLeft) \(lastRight)"
  })
  let disposable = observable.subscribe(onNext: { value in
    print(value)
  })

  // 2
  print("> Sending a value to Left")
  left.onNext("Hello,")
  print("> Sending a value to Right")
  right.onNext("world")
  print("> Sending another value to Right")
  right.onNext("RxSwift")
  print("> Sending another value to Left")
  left.onNext("Have a good day,")

  disposable.dispose()
}
--- Example of: combineLatest ---
> Sending a value to Left
> Sending a value to Right
Hello, world
> Sending another value to Right
Hello, RxSwift
> Sending another value to Left
Have a good day, RxSwift

combine user choice and value

example(of: "combine user choice and value") {
  let choice : Observable = Observable.of(.short, .long)
  let dates = Observable.of(Date())

  let observable = Observable.combineLatest(choice, dates) {
    (format, when) -> String in
    let formatter = DateFormatter()
    formatter.dateStyle = format
    return formatter.string(from: when)
  }

  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: combine user choice and value ---
7/11/17
July 11, 2017

zip

绑定超过最多不超过8个的Observable流,结合在一起处理。注意Zip是一个事件对应另一个流一个事件。
• Subscribed to the observables you provided.
• Waited for each to emit a new value.
• Called your closure with both new values.


RxSwift_v1.0笔记——9: Combining Operators_第5张图片
zip
example(of: "zip") {
  enum Weather {
    case cloudy
    case sunny
  }
  let left: Observable = Observable.of(.sunny, .cloudy, .cloudy, .sunny)
  let right = Observable.of("Lisbon", "Copenhagen", "London", "Madrid", "Vienna")

  let observable = Observable.zip(left, right) { weather, city in
    return "It's \(weather) in \(city)"
  }
  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: zip ---
It's sunny in Lisbon
It's cloudy in Copenhagen
It's cloudy in London
It's sunny in Madrid

Triggers

withLatestFrom

When button emits a value, ignore it but instead emit the latest value received from the simulated text field.

RxSwift_v1.0笔记——9: Combining Operators_第6张图片
withLatestFrom

sample

前面同withLatestFrom,只是点击时textfield没有更新值就不发出
It does nearly the same thing with just one variation: each time the trigger observable emits a value, sample(:) emits the latest value from the “other” observable, but only if it arrived since the last “tick”. If no new data arrived, sample(:) won’t emit anything.

RxSwift_v1.0笔记——9: Combining Operators_第7张图片
sample
example(of: "withLatestFrom") {
  // 1
  let button = PublishSubject()
  let textField = PublishSubject()

  // 2
   let observable = button.withLatestFrom(textField)
//  let observable = textField.sample(button)
  let disposable = observable.subscribe(onNext: { value in
    print(value)
  })

  // 3
  textField.onNext("Par")
  textField.onNext("Pari")
  textField.onNext("Paris")
  button.onNext()
  button.onNext()
}
--- Example of: withLatestFrom ---
Paris
Paris
--- Example of: sample ---
Paris

Switches

RxSwift comes with two main so-called “switching” operators: amb(_:) and switchLatest(). They both allow you to produce an observable sequence by switching between the events of the combined or source sequences. This allows you to decide which sequence's events will the subscriber receive at runtime.

amb——ambiguous

开始,你不知道要订阅谁。谁先发送,就取消另一个的订阅
The amb(_:) operator subscribes to left and right observables. It waits for any of them to emit an element, then unsubscribes from the other one. After that, it only relays elements from the first active observable.


RxSwift_v1.0笔记——9: Combining Operators_第8张图片
amb
example(of: "amb") {
  let left = PublishSubject()
  let right = PublishSubject()

  // 1
  let observable = left.amb(right)
  let disposable = observable.subscribe(onNext: { value in
    print(value)
  })

  // 2
  right.onNext("Copenhagen")
  left.onNext("Lisbon")
  left.onNext("London")
  left.onNext("Madrid")
  right.onNext("Vienna")

  disposable.dispose()
}
--- Example of: amb ---
Copenhagen
Vienna

switchLatest

可以对事件流进行转换,本来监听的subject1,我可以通过更改variable里面的value更换事件源。变成监听subject2了


RxSwift_v1.0笔记——9: Combining Operators_第9张图片
switchLatest
example(of: "switchLatest") {
  // 1
  let one = PublishSubject()
  let two = PublishSubject()
  let three = PublishSubject()

  let source = PublishSubject>()

  // 2
  let observable = source.switchLatest()
  let disposable = observable.subscribe(onNext: { value in
    print(value)
  })

  // 3
  source.onNext(one)
  one.onNext("Some text from sequence one")
  two.onNext("Some text from sequence two")

  source.onNext(two)
  two.onNext("More text from sequence two")
  one.onNext("and also from sequence one")

  source.onNext(three)
  two.onNext("Why don't you seem me?")
  one.onNext("I'm alone, help me")
  three.onNext("Hey it's three. I win.")

  source.onNext(one)
  one.onNext("Nope. It's me, one!")

  disposable.dispose()
}
--- Example of: switchLatest ---
Some text from sequence one
More text from sequence two
Hey it's three. I win.
Nope. It's me, one!

Combining elements within a sequence

reduce

只有在observable completes时,才发出值
This is much like what you’d do with Swift collections, but with observable sequences.
reduce(::) produces its summary (accumulated) value only when the
source observable completes.

RxSwift_v1.0笔记——9: Combining Operators_第10张图片
reduce

example(of: "reduce") {
  let source = Observable.of(1, 3, 5, 7, 9)

  // 1
  // 1
  let observable = source.reduce(0, accumulator: { summary, newValue in
    return summary + newValue
  })

  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: reduce ---
25

scan

You get one output value per input value. As you may have guessed, this value is the running total accumulated by the closure.

RxSwift_v1.0笔记——9: Combining Operators_第11张图片
scan
example(of: "scan") {
  let source = Observable.of(1, 3, 5, 7, 9)

  let observable = source.scan(0, accumulator: +)
  observable.subscribe(onNext: { value in
    print(value)
  })
}
--- Example of: scan ---
1
4
9
16

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