Future with asynchronous resolve does not fire

Viewed 126

I am currently trying to learn Swift+Combine, but I even fail at replicating a simple tutorial.

My current playground project looks as follows:

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($0) },
            receiveValue: { print($0) })

print("end")

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

I would have expected as output:

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

But when I run this code, the output only displays:

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

It seems to swallow the whole sink. At first I thought maybe the future was already deleted by the time the DispatchQueue fired its callback, but this does not seem to be the case.

Can someone explain to me what I am doing wrong?

1 Answers

You need to store a reference to the subscription you create with sink, otherwise the subscription and hence the subscriber gets deallocated straight away and hence there won't be any values emitted from Future, the Publisher.

let futureSubscription = future.sink(receiveCompletion: { print($0) },
        receiveValue: { print($0) })
Related