Last active
July 30, 2019 15:19
-
-
Save GeekTree0101/2e0dd07b62dcf61abf07605cc7d573c8 to your computer and use it in GitHub Desktop.
PromiseRepository
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
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 | |
} | |
} |
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
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