Created
September 17, 2019 09:08
-
-
Save achernoprudov/0f3c5ce1bdebb426480e70c582390511 to your computer and use it in GitHub Desktop.
RxSwift endless paginator template
This file contains hidden or 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
class Paginator { | |
struct Params { | |
let firstIndex: Int | |
} | |
let initParams: Params | |
private let pageSubject = PublishSubject<Void>() | |
init(params: Params) { | |
self.initParams = params | |
} | |
func loadNext() { | |
pageSubject.onNext(()) | |
} | |
func start() -> Observable<[String]> { | |
return load(params: initParams, accumulator: []) | |
} | |
private func load( | |
params: Params, | |
accumulator: [String] | |
) -> Observable<[String]> { | |
return request(params.firstIndex) | |
.flatMap { [pageSubject] (result) -> Observable<[String]> in | |
let newParams = Params(firstIndex: params.firstIndex + result.count) | |
let resultObservable = Observable.just(accumulator + result) | |
let allObjects = accumulator + result | |
return Observable.concat( | |
Observable.just(allObjects), // fetched page observable | |
Observable.never().takeUntil(pageSubject), // paginator controller observable | |
self.load(params: newParams, accumulator: allObjects) | |
) | |
} | |
} | |
private func request(_ firstIndex: Int) -> Observable<[String]> { | |
// here has to be repository call | |
let result = (firstIndex...(firstIndex+2)).map { $0.description } | |
return Observable.just(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment