Last active
November 29, 2017 01:06
-
-
Save cjnevin/fef9007fee3fbb17f3ed93069343ca05 to your computer and use it in GitHub Desktop.
Return a paged list of results from a repository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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