0
votes

I'm new to RxSwift trying to find out the simplest way to achieve the following:

  • After login to the app a first 'getData' request is done. This data is critical and will be loaded behind a spinner. When received, the data is saved in a Core Data db. When this task is finished (using completion block) the next request is started which should run asynchronously in background, the data here is also saved in the db. A spinner should be shown if the view presenting the latter data is accessed and the data has not yet been received and fetched from db.

Model

let subject = ReplaySubject<[MyObject]>.create(bufferSize: 3)
var observable : Observable<[MyObject]>?

 init() {
        self.observable = subject
 }
 ...

 self?.insertFirstDataToDb(firstData){
   self?.api.getNextData(param,  success: { (data) -> Void in
    self?.insertNextDataToDb(firstData)

  })
  ... 
}

ViewController

override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        // show spinner if data is not available yet
        self.myModel?.observable?
            .subscribe(onNext : { (additionalData) in
                self.updateMyTab(additionalData)
               // hide spinner
        })
        .disposed(by: self.disposeBag)
}

I suppose this can be done without using RxSwift, would there be any performance issues? Any suggestions how to solve this?

1

1 Answers

0
votes

To start and stop the spinner you can respectively use onSubscribed and onNext closures of the do operator.

To channel multiple requests one after another I would recommend do use flatMapLatest operator. For a good design you can develop a decorator for the request that will launch the spinner when the request is subscribed to.