Vala: How to asynchronously wait for x seconds and execute something then

444 Views Asked by At

I want to implent a "type to start search"-feature like the google search in my program. After every type my program starts a new search thread and kills the old one.

But now I want to wait for example 2 seconds before the search thread does actually starts. Something like this:

Countdown countdown = new Countdown();
countdown.set_action_after_x_secons(2sec, do_search);


private void SearchEntry_search_changed(){
    countdown.reset_time(); //resets time to 2 seconds again
    actual_search = SearchEntry.get_text();
}

private void do_search(){
// actual search here
}

I want to avoid to spawn to many useless threads. What is the best way to do this in Vala?

1

There are 1 best solutions below

0
On

Thanks to @andlabs! GLib.Timeout was the keyword. For solution see here:

    private int search_delay = 1000;
    private uint delayed_changed_id;

    public void search(string txt){
        search_text = txt;
        reset_timeout();
    }

    private void reset_timeout(){
        if(delayed_changed_id > 0)
            Source.remove(delayed_changed_id);
        delayed_changed_id = Timeout.add(search_delay, timeout);
    }

    private bool timeout(){
        // do actual search here!

        delayed_changed_id = 0;

        return false;
    }