I'm using playground to experiment with Combine. I found this example on a blog. I expect it to create the Future publisher, wait a couple seconds then send the promise and complete.
import Foundation
import Combine
import SwiftUI
let future = Future<Int, Never> { promise in
print("Creating")
DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
print("sending promise")
promise(.success(1))
}
}
future
.sink(receiveCompletion: { print("receiveCompletion:\($0)") },
receiveValue: { print("receiveValue:\($0)") })
print("end")
The output I expect:
Creating
end
sending promise
receiveValue: ...
receiveCompletion: ...
The output I get:
Creating
end
sending promise
I don't see an indication the promise was executed. What am I doing wrong?
Please try something like this:
import Foundation
import Combine
import SwiftUI
let future = Future<Int, Never> { promise in
print("Creating")
DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
print("sending promise")
promise(.success(1))
}
}
let cancellable = future //<-
.sink(receiveCompletion: { print("receiveCompletion:\($0)") },
receiveValue: { print("receiveValue:\($0)") })
print("end")
It seems the result of future.sink
needs to be held in a strong reference until the operation is completed.