0

I'm learning Apple Combine in a Swift macOS command-line application but sometimes I struggle to experiment with asynchronous code and/or with reactive concepts. For instance, in the following example, the publisher is supposed to emit values every 1 second forever and the subscriber simply prints them to the console.

I store the reference to the cancelable object in a variable to avoid ARC canceling the pipeline when the variable ref. count goes to 0. However, in this example, nothing is printed on the console.

Is this due to the reference going out of scope right after the pipeline started so it is canceled right away? In this case, how to hold the reference long enough for the code to work?

import Foundation
import Combine

let cancellable = Timer.publish(every: 1.0, on: .main, in: .common)
    .autoconnect()
    .scan(0) { i, _ in i + 1 }
    .sink { i in
        print(i)
    }

I tried to inspect what's going on with handleEvents():

let output = Timer.publish(every: 1.0, on: .main, in: .common)
    .autoconnect()
    .scan(0) { i, _ in i + 1 }
    .handleEvents(receiveSubscription: { _ in
        print("Received subscription")
    }, receiveOutput: { _ in
        print("Received output")
    }, receiveCompletion: { _ in
        print("Received completion")
    }, receiveCancel: {
        print("Received cancel")
    }, receiveRequest: { demand in
        print("Received demand: \(demand)")
    })
    .sink { i in
        print(i)
    }

And the output is:

Received subscription
Received demand: unlimited
Program ended with exit code: 0
Louis Lac
  • 5,298
  • 1
  • 21
  • 36
  • 1
    To run asynchronous stuff in a CLI you need a runloop. – vadian Jun 03 '21 at 10:55
  • Does this answer your question? [How to prevent a Command Line Tool from exiting before asynchronous operation completes](https://stackoverflow.com/questions/31944011/how-to-prevent-a-command-line-tool-from-exiting-before-asynchronous-operation-co) – Lauren Yim Jul 10 '21 at 23:59

0 Answers0