Observable, subscribe, dispose, filter in actual combat RxSwift

Observable life cycle

Insert picture description here

In the image above, 9 elements can be observed to be emitted. When an observable object emits an element, it emits it in the next event.

ObservableIssue three tap events and then end. This is called an completedevent.

The observable object emits erroran event containing an error. If an observable object emits an errorevent, it will also terminate and cannot emit any other events.

An event that observableemits the nextcontaining element.

Initialize the environment

Create a project named RXSwiftDemo, at the command line pod init, the podfilefill in the following and run pod install.

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'RXSwiftDemo' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for RXSwiftDemo
  pod 'RxSwift', '6.1.0'
  pod 'RxCocoa', '6.1.0'

  target 'RXSwiftDemoUITests' do
    pod 'RxBlocking', '6.1.0'
    pod 'RxTest', '6.1.0'
  end

end

workspaceYou can open it for actual combat.

Create observable

Insert picture description here

justName it aptly, because all it does is create an justobservable sequence of a single element.

The operator creates an observable instance of the individual type from a regular array of elements from.

You can ofuse it to create observablean array or create a single type of observable array.

The following example can be distinguished just, ofand from.

 let one = 1
  let two = 2
  let three = 3
  /// This is a singe element observable
  let observable: Observable<Int> = Observable<Int>.just(one)
  
  /// This is an observable of individual type instances from a array
  let observable2 = Observable.of(one, two, three)
  
  /// This is an observables array using of to create
  let observable3 = Observable.of([one, two, three])
  
  /// This is an observable of individual type instances from a array
  let observable4 = Observable.from([one, two, three])

Subscribe to observations subscribe

Insert picture description here
The observer is used to listen to the event, and then it needs this event to respond. For example: the pop-up prompt box is the observer, which responds to the event of clicking the button.

Subscribing RxSwiftto observables is very similar; you call observable subscribing.

Therefore addObserver(), you can use instead subscribe().

Unlike NotificationCenterdevelopers who usually only use their .defaultsingleton instances, Rxeach observable instance in is different.

More importantly, observableonly subscribers can send events.
Examples of observable variables

let one = 1
  let two = 2
  let three = 3
  /// This is an observable of individual type instances from a array
  let observable = Observable.of(one, two, three)
  
  /// Subscribes an element handler
  observable.subscribe(onNext: {
    
     element in
    print(element) // Result will be: 1,2,3
  })
  
  /// Subscribes an event handler to an observable sequence.
  observable.subscribe {
    
     event in
    print(event) // Result will be: next(1) next(2) next(3) completed
  }

The emptyoperator of creates an empty observable sequence with zero elements. It will only emit one .completedevent.

let observable = Observable<Void>.empty()
    observable
      .subscribe(
        onNext: {
    
     element in
          print(element)
      },
        /// When empty an observable, it will go to completed block
        onCompleted: {
    
    
          print("Completed")
      }
    )

neverCreate an observable in operation that does not emit anything and never terminates

/// If never an observable, it will not emit anything
let observable = Observable<Any>.never()
    observable
      .subscribe(
        onNext: {
    
     element in
          print(element)
      },
        onCompleted: {
    
    
          print("Completed")
      }
    )

Dispose and terminate dispose

Insert picture description here

To unsubscribe explicitly, call dispose()it. After unsubscribing or unsubscribing, the disposecurrent example observablewill stop emitting events

let observable = Observable.of("A", "B", "C")
  let subscription = observable.subscribe {
    
     event in
    print(event)
  }
  /// When dispose, the observable can not emit anything
  subscription.dispose()

It would be tedious to manage each subscription individually, so RxSwiftinclude a DisposeBagtype. The disposal bag can contain .disposed(by: disposeBag)the disposable items that are usually added using this method, and dispose()each disposal bag will be called when the disposal bag is about to be released.

let disposeBag = DisposeBag()
        Observable.of("A", "B", "C")
            .subscribe {
    
    
            print($0)
            }.disposed(by: disposeBag)

The createoperator has a parameter named subscribe. Its job is to provide an implementation of observable call subscriptions.
Use createcustom observable

let disposeBag = DisposeBag()
Observable<String>.create {
    
     (observer) -> Disposable in
            observer.onNext("1")
            observer.onNext("?")
            
            return Disposables.create()
        }.subscribe(
            onNext: {
    
     print($0) },
            onError: {
    
     print($0) },
            onCompleted: {
    
     print("Completed") })
        .disposed(by: disposeBag)

Operator-Operator-Filter

Operators can help you create a new sequence, or change and combine the original sequence to generate a new sequence.

We have used operators many times in the input validation example before. For example, use the map method to convert the entered user name to whether the user name is valid. Then use this converted sequence to control whether the red prompt is hidden. We also use the combineLatest method to combine whether the user name is valid and whether the password is valid to be valid at the same time. Then use this synthesized sequence to control whether the button is clickable.

Here map and combineLatest are both operators, they can help us construct the required sequence. Now, let’s look at a few more examples:
Insert picture description here
filter-filter
Insert picture description here

let disposeBag = DisposeBag()
let rxTemperature: Observable<Double> = Observable.of(10.0, 11.0, 20.0, 35.0, 40.0)
        rxTemperature.filter {
    
     temperature in
            temperature > 33
        }.subscribe(onNext: {
    
     temperature in
            print("high temperature \(temperature)°")
        }).disposed(by: disposeBag)

Build an observable factory

deferred Delay reading the value until subscribed.

deferredThere is a feature to remember. Every time there is a new observer, it deferredwill be created from its closure Observable. This means that subscribing 2 times will create 2 observables. It will affect performance, but it is unlikely that
deferredit will help when subscribing to the long calculation function (if you use createor, it will block just)

let disposeBag = DisposeBag()
var flip = false
        
        let factory: Observable<Int> = Observable.deferred {
    
     () -> Observable<Int> in
            flip = !flip
            
            if flip {
    
    
                return Observable.of(1, 2, 3)
            } else {
    
    
                return Observable.of(4, 5, 6)
            }
        }
        
        for _ in 0...1 {
    
    
            factory.subscribe(onNext: {
    
    
                print($0, terminator: " ... ")
            }).disposed(by: disposeBag)
            print()
        }

reference

https://medium.com/@duydtdev/observables-in-rxswift-f2f451df49b7

https://beeth0ven.github.io/RxSwift-Chinese-Documentation/content/rxswift_core/observable.html

https://github.com/ReactiveX/RxSwift

Guess you like

Origin blog.csdn.net/zgpeace/article/details/114047278