Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

swift - how can i throttle changes to stateobject in swiftui

I have a view performing expensive updates so I'd like to throttle them:

currently my view is like this:

struct CodeGenerationView: View {
    @StateObject var root: RootState
    var body: some View {
        Text(CodeGenerator.generate(root: root))
    }
}

so it is called on each update.

I'd like to throttle the changes to update only once a second

is this possible?

question from:https://stackoverflow.com/questions/65880240/how-can-i-throttle-changes-to-stateobject-in-swiftui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you can move the code generation into the ObservableObject itself, that would be the easiest:

class RootState : ObservableObject {
    @Published var result : String = ""
    
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        Timer.publish(every: 1, on: .main, in: .default)
            .autoconnect()
            .sink { (_) in
                //perform some expensive calculation here
                self.result = "(Date().timeIntervalSince1970)"
            }
            .store(in: &cancellables)
    }
}

struct CodeGenerationView: View {
    @StateObject var root: RootState
    var body: some View {
        Text(root.result)
    }
}

Note that I'm using Combine to connect the timer publisher. If for some reason you couldn't do your code generation inside your RootState, using Combine to connect Publishers together is probably the way to go. You almost certainly won't actually need it in this case, but there's even a throttle method: https://developer.apple.com/documentation/combine/fail/throttle(for:scheduler:latest:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...