Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Last active November 29, 2017 01:06
Show Gist options
  • Save cjnevin/fef9007fee3fbb17f3ed93069343ca05 to your computer and use it in GitHub Desktop.
Save cjnevin/fef9007fee3fbb17f3ed93069343ca05 to your computer and use it in GitHub Desktop.
Return a paged list of results from a repository
import RxSwift
struct List {
struct Item {
let name: String
}
let items: [Item]
}
protocol GetListRepository {
func get(uniqueId: String, startingAt offset: Int, limit: Int) -> Single<List>
}
struct GetListUseCase {
enum Result {
case success(List)
case failure(Error, Int)
}
private let repository: GetListRepository
private let pageSize = 24
private let uniqueId: String
init(uniqueId: String, repository: GetListRepository) {
self.uniqueId = uniqueId
self.repository = repository
}
func getList(with nextPageTrigger: Observable<Void>) -> Observable<Result> {
return nextPageTrigger
.scan(0) { $0.0 + self.pageSize }
.startWith(0)
.flatMap(getPageStartingAt)
}
private func pageIndex(at offset: Int) -> Int {
return offset / pageSize
}
private func getPageStartingAt(_ offset: Int) -> Observable<Result> {
let currentPageIndex = pageIndex(at: offset)
return repository.get(uniqueId: uniqueId, startingAt: offset, limit: pageSize)
.map(Result.success)
.catchError { .just(Result.failure($0, currentPageIndex)) }
.asObservable()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment