Quantcast
Channel: 懒得折腾
Viewing all articles
Browse latest Browse all 764

Loading data from multiple sources with RxSwift

$
0
0

You shouldn’t be using .Error like that. That’s not really conceptually an error case. There’s just nothing in the cache. That’s a common situation. Nothing went “wrong” out of the ordinary. Instead, just send a .Completed event.

As for why your code isn’t working, it’s because an error coming from an Observable included in the concat will become an error on the final concat Observable. The thing to remember with Rx is that once there’s a .Completed event or (in your case) an .Error event, that’s it, it’s over, no more .Next events (or any events).

So instead, if you use .Completed, your code would work as so:

class Cache {
    func getItem(itemID: Int) -> Observable<Item> {
        return Observable<Item>.create { observer in
            // if not found...
            observer.onCompleted() // you would of course really try to get it
                                   // from the cache first.
            return NopDisposable.instance
        }
    }
}

class Network {
    func getItemN(itemID: Int) -> Observable<Item> {
        return Observable<Item>.create { observer in
            // get some `item` from the network and then..
            observer.onNext(item)
            return NopDisposable.instance
        }
    }
}

let observable = Observable.of(cache.getItem(itemID), network.getItem(itemID)).concat().take(1)

observable.subscribeNext { item in
    print(item)
}


Viewing all articles
Browse latest Browse all 764

Trending Articles