简体   繁体   中英

RxSwift - onError emitted twice

I have been experimenting with RxSwift and I am looking for some help with the correct way of dealing with observers. I have an observer with observing for a Publish Subject .

authPublisherSubject.asObserver()

        .subscribe(onNext: { (status) in

        }, onError: { [unowned self] (error) in

        }, onCompleted: { [unowned self] in

  }).disposed(by: disposeBag)

Following are the responsibilities of this observer

  1. Display Activity Indicator
  2. Hide Activity Indicator
  3. Show Error if any
  4. Proceed if login successful

I subscribe for this observer every time user hits Login Button. Is it approach correct?

If I receive an error, next time when I subscribe to this observer ie next time when the user hits login because of some reason the old error is retained and onError is automatically emitted with the old error. However, as far as I understand Publisher Subject only those events would be emitted which happened after observing.

I am not able to understand what is going on here.

There seem to be a few misconceptions going on here.

First, you don't subscribe to an Observer , you subscribe to an Observable . An Observable is something that can be observed, an observer does the observing. For me, a better way to think about it is that an Observable produces values, and Observer consumes them. So you subscribe to Observable s. Your sample code works because the asObserver() function just returns self . That's unfortunate.

Second, Rx is a declarative approach to programming, not imperative. This means that you setup the Rx chain once only, not "every time a button is tapped." Setup the subscribe just once in the viewDidLoad of the view controller. Now, button taps don't emit error events, so there must be something in the chain that you haven't mentioned that is erring out.

As you mentioned in a comment, if an error gets emitted, it will break the observable chain. There are a few ways to handle this. The first and most obvious is to make sure nothing in the chain can emit an error. Another approach is to wrap the operator that can error out in a flatMap and then either using materialize() or catchError within the flatMap. It's important to stop the error from escaping the flatMap because if it does, it will break the primary chain.

I subscribe for this observer every time user hits Login Button. Is it approach correct?

  • NO, Need to subscribe only one time. On every login click it subscribe again and again hence you received the messages twice. For this you have to add subscription in viewWillAppear method. try this hope it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM