Swift's RxSwift (1)

Source: Internet
Author: User
Tags emit

Rxswift Official Document Structure
    1. Introduction:
    2. Subjects
    3. Transforming observables
    4. Filtering observables
    5. Combining observables
    6. Error handing Operators
    7. Observable Utility Operators
    8. Conditional and Boolean Operators
    9. Mathematical and Aggregate Operators
    10. connectable Observable operatiors

Observable

Observable is the observed object in the observer pattern, which is the equivalent of an event sequence (Generatortype) that sends the newly generated event information to the Subscriber.

Event information is divided into:

.Next(value): 表示新的事件数据.Completed: 表示事件序列完结.Error: 异常导致的事件序列完结

Subjects

A Subject is a sort of bridge or proxy, that's available in some implementations of Reactivex, acts both as an observe R and as an Observable.

Subject can be seen as a proxy and a bridge. It is both a subscriber and a feed, which means that it can subscribe to other observables while sending events to his subscribers

1. How to Create observables?
  1. Empty

    empty creates an empty sequence. The only message it sends is the .Completed message.let emptySequence = Observable<Int>.empty()
  2. Never:

    never creates a sequence that never sends any element or completes.let neverSequence = Observable<Int>.never()
  3. Just (one element)

    just represents sequence that contains one element. It sends two messages to subscribers. The first message is the value of single element and the second message is .Completed.let singleElementSequence = Observable.just(32)
  4. Sequenceof (a series of elements)

    sequenceOf creates a sequence of a fixed number of elements.
  5. From (Convert Swift sequence (Sequencetype) to event sequence)

    from creates a sequence from SequenceTypelet sequenceFromArray = [1, 2, 3, 4, 5].toObservable()
  6. Create (creates a sequence from a closure)

    create creates sequence using Swift closure. This examples creates custom version of just operator.let myJust = { (singleElement: Int) -> Observable<Int> in    return Observable.create { observer in    observer.on(.Next(singleElement))    observer.on(.Completed)    return NopDisposable.instance    }}let subscription = myJust(5)    .subscribe { event in        print(event)}
  7. Generate

    generate creates sequence that generates its values and determines when to terminate based on its previous values.let generated = Observable.generate(    initialState: 0,    condition: { $0 < 3 },    iterate: { $0 + 1 })let subscription = generated   .subscribe { event in    print(event)}
  8. Failwith

    create an Observable that emits no items and terminates with an errorlet error = NSError(domain: "Test", code: -1, userInfo: nil)let erroredSequence = Observable<Int>.error(error)
  9. Deferred (load delay, the content of subscribers is identical and completely independent)

    do not create the Observable until the observer subscribes, and create a fresh Observable for each observer
2. How to Create subjects
  1. Publishsubject (the sequence of events after the Subscriber is sent)

     
  2. Replaysubject (when a new subscription is subscribed to all the data columns that have been sent, Buffize: is the size of the buffer, 1 o'clock, then the new Subscriber appears when the replacement of the previous event, if it is 2, the replacement of 2, ...)

    replaysubject emits to any observer all of the items Thatwere Emitted by the source Observable (s), regardless of the observer subscribes.example ("Replaysubject") {Let Disposeb AG = Disposebag () Let subject = Replaysubject<string>.create (buffersize:1) writesequencetoconsole ("1", Sequen Ce:subject). Adddisposableto (Disposebag) Subject.on (. Next ("a")) Subject.on (. Next ("B")) Writesequencetoconsole ("2", Sequence:subject). Adddisposableto (Disposebag) Subject.on (. Next ("C")) Subject.on (. Next ("D"))}print:1-a1-b2-b//reissue of 1 1-c2-c1-d2-d  
  3. Behaviorsubject (the most recently sent event is sent back when a new subscription object is subscribed, and if not, a default value is sent)

    when an observer subscribes to a behaviorsubject, it begins by emitting the item most recently emitted by T He source Observable (or a Seed/default value if none have yet been emitted) and then continues to emit any other items emit Ted later by the source Observable (s). Example ("Behaviorsubject") {Let disposebag = Disposebag () Let subject = Behav Iorsubject (value: "Z") writesequencetoconsole ("1", Sequence:subject). Adddisposableto (Disposebag) Subject.on (. Next ("a")) Subject.on (. Next ("B")) Writesequencetoconsole ("2", Sequence:subject). Adddisposableto (Disposebag) Subject.on (. Next ("C")) Subject.on (. Next ("D")) Subject.on (. Completed)}print:1-z1-a1-b2-b1-c2-c1-d2-d1-com2-com  
  4. Variable (is a layer of behaviorsubject-based encapsulation that has the advantage of not being shown the end, i.e.: will not be affected. Complete or. Error Such an end event, it will be active in the destruction of the time to send. complete)

    Variable wraps BehaviorSubject. Advantage of using variable overBehaviorSubject is that variable can never explicitly completeor error out, and BehaviorSubject can in case Error or Completed message is send to it. Variable will also automatically complete in case it‘s being deallocated.example("Variable") {    let disposeBag = DisposeBag()    let variable = Variable("z")    writeSequenceToConsole("1", sequence: variable.asObservable()).addDisposableTo(disposeBag)    variable.value = "a"    variable.value = "b"    writeSequenceToConsole("2", sequence: variable.asObservable()).addDisposableTo(disposeBag)    variable.value = "c"    variable.value = "d"}
3. Transforming observables
    1. Map/select

More info in Reactive.io website

example("map") {    let originalSequence = Observable.of(1, 2, 3)    _ = originalSequence        .map { number in            number * 2        }        .subscribe { print($0) }}

Swift's RxSwift (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.