JavaFX concurrent task setting state JavaFX concurrent task setting state multithreading multithreading

JavaFX concurrent task setting state


Task states are not intended to be used for user logic. They are introduced to control Task flow. To add user logic into Task you need to use result conception. In your case you may want to use Task<Boolean> and result of your task will be TRUE for correct credentials and FALSE for incorrect:

Task creation:

public Task<Boolean> doLogin() {    return new Task<Boolean>() {        @Override        protected Boolean call() {            Boolean result = null;            user.login();            if (!user.getIsAuthorized()) {                result = Boolean.FALSE;            } else {                result = Boolean.TRUE;            }            user.remember();            return result;        }    };}

Starting that task:

final Task<Boolean> login = doLogin();login.setOnSucceeded(new EventHandler<WorkerStateEvent>() {    @Override    public void handle(WorkerStateEvent t) {        // This handler will be called if Task succesfully executed login code        // disregarding result of login operation        // and here we act according to result of login code        if (login.getValue()) {            System.out.println("Successful login");        } else {            System.out.println("Invalid login");        }    }});login.setOnFailed(new EventHandler<WorkerStateEvent>() {    @Override    public void handle(WorkerStateEvent t) {        // This handler will be called if exception occured during your task execution        // E.g. network or db connection exceptions        System.out.println("Connection error.");    }});new Thread(login).start();