【发布时间】:2019-07-30 04:57:00
【问题描述】:
以下面的服务为例
import Foundation
import PromiseKit
protocol ProfileServiceType {
func fetchCurrentUser() -> Promise<Profile>
}
struct ProfileService: ProfileServiceType {
private let httpClient: HTTPClientProtocol
init(httpClient: HTTPClientProtocol) {
self.httpClient = httpClient
}
func fetchCurrentUser() -> Promise<Profile> {
return httpClient.call(endpoint: ProfilesEndpoint.byUserId, method: .get, urlParams: nil, queryParams: nil, bodyParams: nil)
}
}
当我获取当前用户时,我会返回他们的个人资料,例如,我的应用中有多个场景可能需要用户个人资料的某些方面,例如他们的userId。每次我使用此方法时,它都会发出网络请求。由于此调用是在我的应用首次启动时进行的,因此我可以肯定地说,在任何其他场景或服务需要它之前,我已经获取了这些数据。
我在想这样的事情,但是我需要实现一个我相信的单例模式
var cachedProfile: Profile?
func fetchCurrentUser() -> Promise<Profile> {
return Promise<Profile> { [weak self] seal in
return httpClient.call(endpoint: ProfilesEndpoint.byUserId, method: .get, urlParams: nil, queryParams: nil, bodyParams: nil)
.done { (value: Profile) in
self?.cachedProfile = value
seal.fulfill(value)
}.catch { err in
seal.reject(err)
}
}
}
最近来自 F/E 开发并大量使用 redux,这对我来说是新事物,在处理 iOS 开发时我不是很清楚。
【问题讨论】: