Example 1: Future is one-shot
let pub = Future<Int, Never> { promise in
promise(.success(1))
promise(.success(2))
}
pub.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
// print: 1
Example 2: Future result should be stored in a variable or the subscriber get cancelled immediately that you cannot see the delayed execution.
let pub = Future<Int, Error>{ promise in
DispatchQueue.main.asyncAfter(deadline:.now() + 2) {
promise(.success(1))
}
}
// if you don't have the variable "can", then you will not see the result since the subscriber get cancelled immediately.
let can: AnyCancellable? = pub.sink(receiveCompletion: {
print("\($0)")
}, receiveValue: {
print("\($0)")
})