异步解析的未来不会触发

Future with asynchronous resolve does not fire

我目前正在尝试学习Swift+Combine,但我什至无法复制一个简单的教程。

我当前的 playground 项目如下所示:

import Combine
import Foundation

let future = Future<Int, Never> { promise in
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        print("hello")
        promise(.success(1))
    }
}

future.sink(receiveCompletion: { print([=10=]) },
            receiveValue: { print([=10=]) })

print("end")

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    print(future)
}

我期望输出:

end
hello
1
finished
Combine.Future<Swift.Int, Swift.Never>

但是当我运行这段代码时,输​​出只显示:

end
hello
Combine.Future<Swift.Int, Swift.Never>

好像要吞下整个水槽。起初我以为未来可能在 DispatchQueue 触发其回调时已经被删除,但事实并非如此。

有人可以向我解释我做错了什么吗?

您需要存储对使用 sink 创建的订阅的引用,否则订阅和订阅者会立即被释放,因此 Future 不会发出任何值, Publisher.

let futureSubscription = future.sink(receiveCompletion: { print([=10=]) },
        receiveValue: { print([=10=]) })