RxSwift_v1.0笔记——9: Combining Operators

Prefixing and concatenating

startWith

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


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直接完成了,所以相当于直接链接

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流,根据时间轴发出对应的事件


merge
example(of: "merge") {
  // 1
  let left = PublishSubject<String>()
  let right = PublishSubject<String>()

  // 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.


combineLatest
example(of: "combineLatest") {
  let left = PublishSubject<String>()
  let right = PublishSubject<String>()

  // 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<DateFormatter.Style> = 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.


zip
example(of: "zip") {
  enum Weather {
    case cloudy
    case sunny
  }
  let left: Observable<Weather> = 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.

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.

sample
example(of: "withLatestFrom") {
  // 1
  let button = PublishSubject<Void>()
  let textField = PublishSubject<String>()

  // 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.


amb
example(of: "amb") {
  let left = PublishSubject<String>()
  let right = PublishSubject<String>()

  // 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了


switchLatest
example(of: "switchLatest") {
  // 1
  let one = PublishSubject<String>()
  let two = PublishSubject<String>()
  let three = PublishSubject<String>()

  let source = PublishSubject<Observable<String>>()

  // 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.

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.

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,571评论 0 23
  • 并立奇峰一线天, 山中屹立堑石攀。 文人墨客仰观峭, 赞叹吟诗世间罕。
    六月天气阅读 264评论 3 14
  • 有人说结婚了,男人是女人的半边天,可是我不想要这半边天,他乌云密布,压的我喘不过气来,我宁愿只要属于自己的一片晴朗...
    静静King阅读 221评论 0 0
  • 在三节课学习运营已经有两个多月了,在这里学习到了运营入门所应该了解并具备的基础实践技能,遇到了一群很厉害的小伙伴,...
    sysenri阅读 506评论 0 1
  • 文|沐言Aimee 最近让自己都感动的是,千里迢迢跑到山东荣成见认识了3年多的微信好友。这次是我们第一次见面,有种...
    平头姐阅读 699评论 0 1