skip to Main Content

The solution to user Timer.publish() in a Command Line Tool app could be to use RunLoop. But I can figure out how.

If I write the following it doesn’t work more than if I don’t use RunLoop.

RunLoop.current.run()

let subscription = Timer.publish(every: 1.0, on: .main, in: .default)
    .autoconnect()
    .sink { _ in
        print("timer fired")
    }

2

Answers


  1. Chosen as BEST ANSWER

    The solution given by Ole Begemann on swift forums. Thx to him.

    import Combine
    import Foundation
    
    let subscription = Timer.publish(every: 1.0, on: .main, in: .default)
      .autoconnect()
      .sink { _ in
          print("timer fired")
      }
    
    withExtendedLifetime(subscription) {
      RunLoop.current.run()
    }
    

    It seams "withExtendedLifetime(x:,body:)" is needed to avoid compiler to destroy the subscription instance before the RunLoop start.


  2. The problem is merely that you are giving the commands in the wrong order. Try it like this:

    let subscription = Timer.publish(every: 1.0, on: .main, in: .default)
        .autoconnect()
        .sink { _ in
            print("timer fired")
        }
    RunLoop.current.run()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search