Skip to content

Instantly share code, notes, and snippets.

@GeekTree0101
Last active July 30, 2019 15:19
Show Gist options
  • Save GeekTree0101/2e0dd07b62dcf61abf07605cc7d573c8 to your computer and use it in GitHub Desktop.
Save GeekTree0101/2e0dd07b62dcf61abf07605cc7d573c8 to your computer and use it in GitHub Desktop.
PromiseRepository
protocol DataPassing: class {
associatedtype DataSource
var dataSource: DataSource { get set }
}
protocol PromiseRepository: DataPassing {
func syncCache(_ promise: Promise<DataSource>) -> Promise<DataSource>
}
extension PromiseRepository {
func syncCache(_ promise: Promise<DataSource>) -> Promise<DataSource> {
promise.done(on: DispatchQueue.global(), { [weak self] in
self?.dataSource = $0
}).cauterize()
return promise
}
}
import PromiseKit
class HistoryRepository: PromiseRepository {
struct DataSource {
var history: History?
var error: Error?
}
var dataSource: DataSource = .init(history: nil, error: nil)
public func getHistory() -> Promise<DataSource> {
let response = Promise(resolver: { seal in
seal.fulfill(History(id: 1, title: "test", isFollow: true))
})
.map({ history -> DataSource in
var newDataSource = self.dataSource
newDataSource.history = history
newDataSource.error = nil
return newDataSource
})
.recover({ error -> Promise<DataSource> in
var newDataSource = self.dataSource
newDataSource.history = nil
newDataSource.error = error
return Promise.value(newDataSource)
})
return syncCache(response)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment