swift - PromsieKit + Alamofire for loading paged HTTP Data -
i migrating code restkit alamofire. use magicalrecord + alamofireobjectmapper map json coredata objects.
i faced following situation:
my data lives @ url:
http://domain.com/api/resources?start=xx&limit=yy
now have this:
- download first page of data given url using page-size of
50
- if number of loaded objects equal page-size increment
start
parameter page size - if number less page size combine loaded objects , return them callee.
in previous non-alamofire example did use recursion promisekit guess have additional chaining of promises rather recursion of method calls.
so far have done simple chaining of promises conditional looped chaining , how implement using promisekit bit of mystery me.
i did come approach seems work fine. however, have feeling more concise better answers or comments welcome.
i decided combine recursion , promises (due lack of better solutions). passing along currentpromise
chained further more pages need loaded.
the first method starts whole process , created promise instantly fulfilled empty array so: promise([issue]())
:
func loadallpagedissues(repository: repository) -> promise<[issue]>{ return loadpagedissues(repository, limit: config.apipagesize, start: 0, currentpromise: promise([issue]())) }
the next method actual work of downloading content , parsing it.
func loadissues(url: string, repository: repository) -> promise<[issue]>{ return promise{ fullfill, reject in self.manager .request(.get, url, headers: self.headers) .responsearray(keypath: "issues", context: repository) { (response: response<[issue], nserror>) in switch response.result{ case .success(let value): fullfill(value) case .failure(let e): reject(e) } } } }
the final method combines results being passed in , loaded ones. if end of page reached results returned using fullfilled promise , if more pages need loaded call second method issued:
func loadpagedissues(repository: repository, limit: int, start: int, currentpromise: promise<[issue]>) -> promise<[issue]>{ let url = baseurl + config.pagedissuespath.replacetokens( [ "repo": repository.slug, "limit": string(limit), "start": string(start) ] ) let loadpromise = self.loadissues(url, repository: repository) return when(loadpromise, currentpromise).then{ newissues, existingissues -> promise<[issue]> in let combined = promise<[issue]>(newissues + existingissues) if newissues.count < limit{ // reached end of page return combined } else { return self.loadpagedissues(repository, limit: limit, start: (start + limit), currentpromise: combined) } } }
Comments
Post a Comment