G'day everyone, welcome back. The save Timing function's pretty straightforward.
It's code that we've seen before. The only slight complication, is that we need
to decide whether we're saving a new record, or updating an existing one.
If we're saving a new record, it'll have a duration of zero. Any timing instance
that has a non-zero duration means that we want to update the row, rather than add a
new one. I'll put the saveTiming function after timeTask.
We'll put a log statement in just so we know it's going on. We said before, that if we're
inserting, then the currentTiming duration will be zero.
Let's add in the column data.
When we insert a new row in the database, we have to store the ID back into the
timing object, otherwise, we won't be able to update it later.
We've seen that done before, when saving a taskRecord in the saveTask function.
We can improve on that code slightly. The only column that changes when we update,
is a duration. There's no point adding the other two columns to the
content values, in that case.
Alright, I can now uncomment the calls to saveTiming, in our timeTask function.
We've got two errors again, because currentTiming is a nullable type,
and can't be cast to a non-null timing, using a smart cast. We can fix that with the
bangbang operator. We've just created a new instance on the line above, in each case,
so it's not going to be null. I think it's safe to do that, and it's
arguably safer than what I'm about to do for the second error. If you're not a fan
of bangbang - and you certainly should use them sparingly - then another approach is,
change the currentTiming to val newTiming, save the newTiming,
and then assign that to the current timing.
Personally, I don't like using bangbang too much, but I think it's preferable in
this case. If you forget to assign the newTiming back to currentTiming, you'll
have a bug. It's also easier to work out what's happening, in the first case, on
line 106. I'll leave both ways in the code, for comparison. I don't suggest you
do that in your code. Whichever method you prefer, be consistent, especially
inside the same function. In the next video, we'll test the app to make sure
this is working. I'll see you then.