1

I'm having 2 methods like this:

func rxGetAllTonicsForLanguage(language: Language) -> Observable<AnyObject?>
func saveTonics(list: [Tonic]) -> Observable<AnyObject?>

Now I want to first do the getAllTonics call and then with the result of that call I want to do the next action. So I thought this was something I could do with FlatMap. But I'm stuck I can't figure out how to chain these.

I tried like follows:

   self.remoteService.rxGetAllTonicsForLanguage(language)
        .subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
        .flatMap{tonics -> Observable<[Tonic]> in
            print("Tonics: \(tonics)")
            let x = tonics as! [Tonic]
            return TonicAdapter.sharedInstance.saveTonics(x)
    }.observeOn(MainScheduler.instance)
        .subscribe({ e in
            switch e {
            case .Next(let element):
                if let result = element as? String {
                    DDLogDebug("Saved something \(result)")
                }
            case .Error(let e):
                DDLogError("Error in save tonics \(e)")
            case .Completed:
                DDLogDebug("Completed save tonics")
            }
            }
        ).addDisposableTo(self.disposeBag)

It gives me this error on the line of return TonicAdapter:

Cannot convert return expression of type 'Observable<AnyObject?>' (aka 'Observable<Optional<AnyObject>>') to return type 'Observable<[Tonic]>' (aka 'Observable<Array<Tonic>>')

I don't see the problem because both methods are returning Observables?

user1007522
  • 7,858
  • 17
  • 69
  • 113
  • 1
    You need to change the return type declared in `saveTonics` from `Observable` to `Observable<[Tonic]>`. Or you can cast the same change (if you are certain that it will always be the case). – Putz1103 Jul 07 '16 at 17:54
  • Thank you so much. I was so into the code that I didn't saw I wrote it different :-). – user1007522 Jul 08 '16 at 17:30

2 Answers2

2

You need to change the return type declared in saveTonics from Observable to Observable<[Tonic]>. Or you can cast the same change (if you are certain that it will always be the case).

Putz1103
  • 6,211
  • 1
  • 18
  • 25
0
func rxGetAllTonicsForLanguage(language: Language) -> Observable<[Tonic]>
func saveTonics(list: [Tonic]) -> Observable<AnyObject?>

the output of rxGetAllTonicsForLanguage can be passed to saveTonics like this

rxGetAllTonicsForLanguage
    .flatMapLatest(saveTonics)
    .subscribe(...)
    .disposed(by: disposeBag)
Samuel
  • 9,883
  • 5
  • 45
  • 57