Anton
Anton

Reputation: 1419

Primefaces asynchronous autocomplete: reality check

I'm trying to make an autocomplete control to work with multiple sources of data, when they're having different access times. I googled a lot, but found only jquery or desktop solutions, which I was unable to adapt to jsf. My idea, basically, was to use completeMethod to spawn second thread and when it's done to refresh autocomplete list with more results.

This is my xhtml autocomplete component:

<p:autoComplete id="acSimple" value="#{testBean.txt1}" widgetVar="acSimple"
                completeMethod="#{testBean.completeText}" cache="true"/>

and completeMethod bean relevant lines:

private String oldQuery = "";
private List<String> result;

public List<String> completeText(String query) throws Exception {
    if (!oldQuery.equals(query)) {
        oldQuery = query;
        result = bpp.runFastQuery(query);
        Thread thread = new Thread(new SlowTask(query, result));
        thread.start();
        return result;
    } else {
        return result;
    }
}

class SlowTask implements Runnable {
    String str;

    SlowTask(String query, List<String> result) {
        str = query;
        this.result = result;
    }

    List<String> result;

    public void run() {
        try {
            List<String> r = bpp.runSlowQuery(str);
            result.addAll(r);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

I also tried to run PF('acSimple').search(txt1) with when slower thread was finished, both from client side and both from bean, with RequestContext.getCurrentInstance().update(":form1:acSimple"); but this didn't helped me either, it just updates the form without loading the new data.

If it possible at all to achieve what I want here?

Upvotes: 0

Views: 455

Answers (1)

Youans
Youans

Reputation: 5071

I think your code may work refer to this : https://stackoverflow.com/a/17554922/1460591

I think your run method should be like this :

public void run() {
        try {
            List<String> r = bpp.runSlowQuery(str);
            result.addAll(r);
            RequestContext.getCurrentInstance().update("form1:acSimple");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } 

Upvotes: 1

Related Questions