Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-subscribing to an Observable after error

I feel like I'm beginning to get the hang of RxSwift - however I've just hit a roadblock. Here's an object I've built for a demo (I've simplified it before posting to SO). My issue is, when there's a network error during the upload process, all of the subscriptions get disposed of. So when I tap the rightBarButtonItem again, nothing happens.

What's the correct/better way of modelling this? I'm not sure I've grasped the use of PublishSubjects correctly!

let activityIndicator = ActivityIndicator()
let disposeBag = DisposeBag()

let rx_upload = PublishSubject<Void>()
let rx_progress = PublishSubject<RxProgress>()
let rx_uploadComplete = PublishSubject<Look>()

override init() {
    super.init()

    activityIndicator
        .drive(UIApplication.sharedApplication().rx_networkActivityIndicatorVisible)
        .addDisposableTo(disposeBag)

    let upload = rx_upload
        .debug("Upload")
        .flatMapLatest { [unowned self] -> Observable<(JSON?, RxProgress)> in
            return self.upload()
        }
        .share()

    upload
        .map { $0.1 }
        .debug("Upload Progress")
        .bindTo(rx_progress)
        .addDisposableTo(disposeBag)

    upload
        .filter { $0.0 != nil }
        .map { Post(jsonData: $0.0!) }
        .filterNil()
        .debug("Upload Complete")
        .bindTo(rx_uploadComplete)
        .addDisposableTo(disposeBag)

}

func upload() -> Observable<(JSON?, RxProgress)> {
    // ...
}

And in ViewController.swift...

self.navigationItem.rightBarButtonItem?.rx_tap
.bindTo(postUploader.rx_upload)
.addDisposableTo(disposeBag)
like image 974
jonlambert Avatar asked Apr 25 '16 16:04

jonlambert


1 Answers

There are 2 options here:

  1. Prevent observables being disposed because of Error events.
    You can do this by using catchError family.

  2. Re-subscribe immediately by using retry family.

Base on the way you write your code, I assume that no sample code is needed :D

However, be careful that if an Subject receives Error or Completed events, it will no longer send out any further events.

like image 188
Pham Hoan Avatar answered Oct 20 '22 17:10

Pham Hoan