Junior — Middle
Can you explain the concept of Future in the Combine framework and its role in asynchronous operations?
sobes.tech AI
Answer from AI
In Combine, Future is a type of Publisher that represents a deferred asynchronous operation that will complete with either a success value or an error. It is used to wrap one-time asynchronous tasks that return a result in the future.
The main role of Future is to provide a convenient way to integrate asynchronous operations into Combine chains, allowing subscribers to receive the result when it becomes available.
Example of using Future:
import Combine
func fetchData() -> Future<String, Error> {
return Future { promise in
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
let success = true
if success {
promise(.success("Data loaded"))
} else {
promise(.failure(NSError(domain: "Error", code: -1, userInfo: nil)))
}
}
}
}
let cancellable = fetchData()
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("Operation completed")
case .failure(let error):
print("Error: \(error)")
}
}, receiveValue: { value in
print("Received value: \(value)")
})
Thus, Future allows wrapping asynchronous code into a Combine stream, simplifying working with asynchronous operations and error handling.