Learning RxSwift – rewrite Variable

Code example of how to implement prepend and append newer/older items to an existing(already bounded) list.

import Foundation
import RxSwift

func fetchEarlierItemsThan(latestItem: Int?) -> Observable<[Int]> {
    if let latestItem = latestItem {
        return just([latestItem - 1])
    }
    return just([0])
}

func fetchLaterItemsThan(latestItem: Int?) -> Observable<[Int]> {
    if let latestItem = latestItem {
        return just([latestItem + 1])
    }
    return just([0])
}

let prependStream = PublishSubject<Void>()

let appendStream = PublishSubject<Void>()

let currentPostList = Variable([Int]())

let prependItems = prependStream
    .withLatestFrom(currentPostList.asObservable()) { _, prependItems -> Observable<[Int]> in
        return fetchEarlierItemsThan(prependItems.first)
            .map { newItemsToPrepend in newItemsToPrepend + prependItems }
    }
    .switchLatest()
    .subscribeNext {
        currentPostList.value = $0
    }

let appendItems = appendStream
    .withLatestFrom(currentPostList.asObservable()) { _, appendItems -> Observable<[Int]> in
        return fetchLaterItemsThan(appendItems.last)
            .map { newItemsToAppend in appendItems + newItemsToAppend }
    }
    .switchLatest()
    .subscribeNext {
        currentPostList.value = $0
}

currentPostList.subscribeNext {
    NSLog("\($0)")
}

appendStream.onNext(())
prependStream.onNext(())
appendStream.onNext(())
prependStream.onNext(())
prependStream.onNext(())
prependStream.onNext(())

playground output:
2016-01-08 11:46:23.031 Introduction[60454:5285520] []
2016-01-08 11:46:23.035 Introduction[60454:5285520] [0]
2016-01-08 11:46:23.039 Introduction[60454:5285520] [-1, 0]
2016-01-08 11:46:23.042 Introduction[60454:5285520] [-1, 0, 1]
2016-01-08 11:46:23.045 Introduction[60454:5285520] [-2, -1, 0, 1]
2016-01-08 11:46:23.049 Introduction[60454:5285520] [-3, -2, -1, 0, 1]
2016-01-08 11:46:23.052 Introduction[60454:5285520] [-4, -3, -2, -1, 0, 1]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s