SwiftUI Combine Framework: Detecting Double Value Changes with a 1-Second Delay
To achieve this in SwiftUI's Combine framework, you can create a @State property to store the latest value of the publisher, and then use a Timer to reset the value after 1 second. Here's an example:
import SwiftUI
import Combine
class ViewModel: ObservableObject {
@Published var doubleValue: Double = 0.0
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
@State private var hasChanged = false
private var cancellable: AnyCancellable?
var body: some View {
VStack {
Text('Has Changed: (hasChanged.description)')
.padding()
Button('Update Value') {
viewModel.doubleValue = Double.random(in: 0...100)
}
.padding()
}
.onAppear {
cancellable = viewModel.$doubleValue
.sink { value in
if self.hasChanged != (value != 0) {
self.hasChanged = value != 0
resetHasChanged()
}
}
}
}
private func resetHasChanged() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.hasChanged = false
}
}
}
In the above code, the ViewModel class is an ObservableObject that holds the doubleValue as a @Published property. When the Update Value button is pressed, it generates a random double value and assigns it to doubleValue.
In the ContentView, we use a @StateObject wrapper to create an instance of ViewModel. We also use a @State property hasChanged to store the state of whether the doubleValue has changed or not.
Inside the onAppear modifier, we create a subscription to the viewModel.$doubleValue publisher. Whenever the value changes, it checks if the hasChanged state matches the new value. If not, it updates hasChanged and calls resetHasChanged() to reset it to false after 1 second.
The resetHasChanged() function uses DispatchQueue.main.asyncAfter to schedule the reset of hasChanged to false after 1 second.
This approach ensures that hasChanged remains true until 1 second after the last value change.
原文地址: https://www.cveoy.top/t/topic/nLti 著作权归作者所有。请勿转载和采集!