Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Last active February 3, 2018 14:21
Show Gist options
  • Save cjnevin/1826fed3f9ccc7fb086cf34ab74cd26f to your computer and use it in GitHub Desktop.
Save cjnevin/1826fed3f9ccc7fb086cf34ab74cd26f to your computer and use it in GitHub Desktop.
Revised for updating count based on response
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 currentPage = Variable<Int>(0)
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
.withLatestFrom(currentPage.asObservable())
.flatMap(getPageStartingAt)
}
private func pageIndex(at offset: Int) -> Int {
return offset / pageSize
}
private func getPageStartingAt(_ offset: Int) -> Observable<Result> {
let currentPageIndex = self.currentPage.value
return repository.get(uniqueId: uniqueId, startingAt: offset, limit: pageSize)
.do(onNext: { list in
self.currentPage.value = self.pageIndex(at: list.items.count)
})
.map(Result.success)
.catchError {
.just(Result.failure($0, self.currentPage.value)) }
.asObservable()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment