Bobby Redjeans
Bobby Redjeans

Reputation: 599

RXSwift combine two observables and call to API

I'm pretty new in RX, so i'm kind confused how to do it correctly.

My view model:

let feedItems: BehaviorSubject<[FeedItem]> = BehaviorSubject(value: [FeedItem]())
let isLoadingMore: PublishSubject<Bool> = PublishSubject()
let loadPageTrigger: PublishSubject<Void> = PublishSubject()
let isRefreshing: PublishSubject<Bool> = PublishSubject()

func fetchFeed(showLoading: Bool = false, loadMore: Bool = false) {

  //api call and set self.feedItems.onNext(response) after completion

}

In my VC i bind feedItems to collectionView, check when collectionView in bottom and bind it to isLoadingMore, and also bind UIRefresherControl to isRefreshing.

In my ViewModel i want to get value of isRefreshing and isLoadingMore in loadPageTrigger and call fetchFeed with some parameters:

ViewModel:

override init() {
    super.init()
    loadPageTrigger.subscribe(onNext:  {
        // need to get values of isRefreshing and isLoadingMore to call fetchFeed with params
        self.fetchFeed()
    }).disposed(by: disposeBag)
}

Upvotes: 1

Views: 581

Answers (1)

Daniel T.
Daniel T.

Reputation: 33979

Subjects provide a convenient way to poke around Rx, however they are not recommended for day to day use. -- Intro to Rx

If you’re loading up your view model full of Subjects then you haven't quite gotten the grasp of Rx yet. That's okay though, everybody has to start somewhere.

The most direct solution based on what you already have is something like this:

loadPageTrigger
    .withLatestFrom(Observable.combineLatest(isRefreshing, isLoadingMore))
    .subscribe(onNext: { [unowned self] isRefreshing, isLoadingMore in
        // here you have isRefreshing and isLoadingMore as Bools
        self.fetchFeed()
    })
    .disposed(by: disposeBag)

Note the unowned self. It is very important to make sure you aren't capturing self in closures that are being retained by the disposeBag which is held in self.

The optimum solution would involve only Observables and no Subjects at all.

The IObservable<T> interface is the dominant type that you will be exposed to for representing a sequence of data in motion, and therefore will comprise the core concern for most of your work with Rx... -- Intro to Rx

Upvotes: 1

Related Questions