Let's say I have a class named Person, with variables like firstName and lastName. I am listening to changes in these variables using a reactiveCocoa-framework, but let's say I'm only using the built in KVO-listening, like the didSet{}. So assume I have this code:
let firstName:String { didSet{ self.nameDidChange() }}
let lastName: String { didSet{ self.nameDidChange() }}
func nameDidChange(){ print("New name:", firstName, lastName}
Every time I'd change either the first name or the last name, it would automatically call the function nameDidChange.
What I'm wondering, is if there's any smart move here to prevent the nameDidChange function from being called twice in a row when I change both the firstName and the lastName.
Let's say the value in firstName is "Anders" and lastName is "Andersson", then I run this code:
firstName = "Borat"
lastName = "Boratsson"
nameDidChange will be called twice here. It will first print out "New name: Borat Andersson", then "New name: Borat Boratsson".
In my simple mind, I'm thinking I can create a function called something like nameIsChanging(), call it whenever any of the didSet is called, and start a timer for like 0.1 second, and then call nameDidChange(), but both of these didSets will also call nameIsChanging, so the timer will go twice, and fire both times. To solve this, I could keep a "global" Timer, and make it invalidate itself and restart the count or something like that, but the more I think of solutions, the uglier they get. Are there any "best practices" here?