我有一个单例类,该类需要具有异步回调的网络操作才能初始化。该类的任何成员函数仅应在初始化回调完成时调用。
我不清楚的是,在我将单例实例返回给调用者之前,如何等待异步回调完成?也许还有其他方法可以确保在调用任何函数之前完成初始化(仅初始化应该是顺序的,之后的所有操作都不应该是顺序的)。
这是最小的代码:
class DataProvider {
public static let instance: DataProvider {
// on first call wait here until callback is done
// on subsequent calls, no need to wait since already initialized
return internalInstance
}
private static let internalInstance = DataProvider()
private init() {
initialize()
}
private func initialize() {
Something.callAsynch { (result, error) in
// instance becomes ready when this line is executed
}
}
public func doSomething() {
// this function should only run after asynch callback was executed
}
}
此类由其他类以及可能的其他线程调用,例如:
DataProvider.instance.doSomething()
答案 0 :(得分:3)
在一些帮助下,我找到了一个既可靠又简单的好的解决方案。解决方案是使用倒数锁存器。不幸的是,没有像Swift这样的内置类,但是可以在线找到一些实现(例如:this class from Uber)。所以这是一个解决方案:
class DataProvider {
public static let instance: DataProvider {
// on first call wait here until callback is done
// on subsequent calls, no need to wait since already initialized
return internalInstance
}
private static let internalInstance = DataProvider()
private let initLatch = CountDownLatch(1)
private init() {
initialize()
}
private func initialize() {
Something.callAsynch { (result, error) in
// instance becomes ready when this line is executed
initLatch.countDown()
}
}
public func doSomething() {
initLatch.await()
// this function should only run after asynch callback was executed
}
}
那它是怎么做的:
doSomething
的任何调用方都将被挂起,直到锁存器减为0为止doSomething
注意: