HomeiOS Developmentios - Timer will not cease - .upstream.join().cancel()

ios – Timer will not cease – .upstream.join().cancel()


As an alternative of auto connecting, it is advisable join manually and retailer the ensuing Cancellable. That’s the object you later cancel. Additionally, you will have to subscribe to the Timer writer explicitly. You do not have to preserve a reference to the Timer writer — simply the Cancellable. One can find this much more tractable underneath SwiftUI when you preserve the Timer Cancellable in a separate class object.

To be fairly trustworthy I do not see why you employ a Timer writer in any respect; personally, I might simply use an precise Timer. Nonetheless, when you insist on utilizing a writer, this is an instance that illustrates the structure I’ve simply described:

class TimerManager: ObservableObject {
    var cancellables = Set<AnyCancellable>()
    func makeTimerPublisher() -> AnyPublisher<Date, By no means> {
        let timerPublisher = Timer.publish(each: 1, on: .most important, in: .default)
        timerPublisher.join().retailer(in: &cancellables)
        return timerPublisher.eraseToAnyPublisher()
    }
    func cease() {
        cancellables.removeAll()
    }
}

struct ContentView: View {
    @StateObject var timerManager = TimerManager()
    @State var labelText: String = ""
    var physique: some View {
        VStack {
            Textual content(labelText)
            Button("Cease") { timerManager.cease() }
        }
        .onReceive(timerManager.makeTimerPublisher()) { labelText = String(describing: $0) }
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments