Rahul
Rahul

Reputation: 177

Kivy - Need for unschedule for event created using Clock.schedule_once

I am beginning to learn kivy and was just reading the documentation on events but I am unable to understand a certain part of it.

Background

The doc says to use Clock.schedule_once(callback,X) to execute callback after X seconds. However if X is 0, it will execute callback after the next frame.

My Confusion

Now the doc follows to say:

Sometimes you may want to schedule a function to be called only once for the next frame, preventing duplicate calls.

And advices not to do the following -

# First, schedule once.
event = Clock.schedule_once(my_callback, 0)

# Then, in another place you will have to unschedule first
# to avoid duplicate call. Then you can schedule again.
Clock.unschedule(event)
event = Clock.schedule_once(my_callback, 0)

But instead use a trigger -

trigger = Clock.create_trigger(my_callback)
# later
trigger()

Each time you call trigger(), it will schedule a single call of your callback. If it was already scheduled, it will not be rescheduled.

My confusion is why does the first method not work? Isn't the method schedule_once() to execute the callback exactly once? Why is there a possibility of duplicate as mentioned in the first approach?

Upvotes: 0

Views: 484

Answers (1)

John Anderson
John Anderson

Reputation: 39012

The documentation is not saying that the first method will not work, only that it is expensive. And yes, calling schedule_once will execute the callback exactly once, but calling it twice will execute it twice. Their example is saying that you may have two places in your code where you will want to schedule the same event, but only want to execute it once. The trigger simply does the equivalent of the first method, but with less overhead.

Upvotes: 1

Related Questions