RxSwift: combining multiple actions

Let's imagine that we have an array of AnObject instances, and you need to perform the following sequence of actions:

  • send objects to the server through separate calls
  • after step 1 is complete, saves this array to DB in batch mode
  • after step 2 is completed, additional processing is performed for each element.

and we want to receive a signal only after completing all these steps (or an error has occurred). What is the right way to achieve this through RxSwift , and is it really possible?

Please find my prototypes below. Unfortunately, I did not come up with the correct code example for the chain, so there is nothing demo.

func makeAPIRequest(object: AnObject) -> Observable<Void> {
    ...
}

func storeData(data: [AnObject]) -> Observable<Void> {
    ...
}

func additionalProcessing(object: AnObject) -> Observable<Void> { 
    ...
} 

func submitData()
{
   let data: [AnObject] = ...;

   let apiOperations = data.map{ makeAPIRequest($0) };
   let storageOperation = storeData(data);
   let processingOperations = data.map{ additionalProcessing($0) };

   ... // some code to chain steps 1-3
   .subscribe { (event) -> Void in
       // should be called when operations from step 3 finished  
   }.addDisposableTo(disposeBag);
}
+4
1

, makeAPIRequest additionalProcessing Observable<SomeNotVoidType>, storeData Observable<Array>. , :

Observables, . toObservable, :

let apiOperations = data.map{ makeAPIRequest($0) }.toObservable()

merge, Observable, , API . toArray, API :

let resultsArray = apiOperations.merge().toArray()

Observable<Array<ApiResult>>, Next, API . :

let storedResults = resultsArray.flatMap { storeDatabase($0) }

Observables , . , flatMap flatMapLates, , Observable<Observable<SomeType>>.

let additionalProcessingResults = storedResults.flatMap {
      return $0.map(additionalProcessing).toObservable()
    }.flatMapLatest { return $0 }

( - ):

additionalProcessingResults.subscribe { (event) -> Void in
       // should be called when operations from step 3 finished  
   }.addDisposableTo(disposeBag);

, , , .

+8

Source: https://habr.com/ru/post/1628346/


All Articles