ios – SwiftUI: Timer with begin and cease not working


I’ve to animate after each 10 secs and I am utilizing Timer.publish and making an attempt to cease timer if I push to a different display screen and begin once more timer on pops again to the identical display screen.

However even after cancel(), I can see logs within the sink technique. Let me know the right method to deal with it.

struct MyView: View {
   
    @StateObject non-public var viewModel = QRCodeScanViewModel()
   
    var physique: some View {
      parentView
         .onAppear {
            viewModel.playPulseAnimation()
         }
         .onDisappear(carry out: viewModel.removePulseAnimation)
    }
}
remaining class MyAnimationClass: ObservableObject {
    
    non-public(set) var timer = Timer.publish(each: 10, tolerance: 0.5, on: .predominant, in: .widespread).autoconnect()
    
    @Printed var shouldPlayPulseAnimation = false

    non-public var cancellables = Set<AnyCancellable>()

    init() {
     ..
     ...

        timer
            .sink(receiveValue: { [weak self] _ in
                print("TIMER SINK")
                self?.shouldPlayPulseAnimation = true
            })
            .retailer(in: &cancellables)
    }

    func playPulseAnimation(isFirstTime: Bool = false) {
        let delay: DispatchTime = .now() + (isFirstTime ? 15 : 0)
        print("playPulseAnimation:", delay)
        DispatchQueue.predominant.asyncAfter(deadline: delay) { [weak self] in
            guard let this = self else {
                return
            }
            this.timer = Timer.publish(each: 10, tolerance: 0.5, on: .predominant, in: .default).autoconnect()
        }
    }

    func removePulseAnimation() {
        print("removePulseAnimation")
        shouldPlayPulseAnimation = false
        timer.upstream.join().cancel()
    }
}

See also  ios - Unrecognized selector error from calling a perform on a timer

Leave a Reply