Pause an AsyncTask until a task is completed

1

In my AsyncTask I instantiate 4 new objects, but I have to stay in it until all objects are brought. Here is the code:

@Override
protected Void doInBackground(Void... voids) {

    new CrtlComentario(contexto).trazer(post.getCodigo(), new CallbackTrazer() {
        @Override
        public void resultadoTrazer(Object obj) {
            c = (Comentario) obj;
            flag[3] = false;
        }

        @Override
        public void falha() {
            flag[3] = false;
        }

    });

    new CrtlUsuario(contexto).trazer(c.getUsuarioPost(), new CallbackTrazer() {
        @Override
        public void resultadoTrazer(Object obj) {
            u = (Usuario) obj;
            flag[0] = false;
        }

        @Override
        public void falha() {
            flag[0] = false;
        }
    });

    new CrtlComentarioPost(contexto).listar(new CallbackListar() {
        @Override
        public void resultadoListar(List<Object> lista) {
            for (Object obj : lista)
                cp.add((ComentarioPost) obj);
            flag[1] = false;
        }

        @Override
        public void falha() {
            flag[1] = false;
        }
    });

    new CrtlCurtidaComentario(contexto).listar(new CallbackListar() {
        @Override
        public void resultadoListar(List<Object> lista) {
            for (Object obj : lista)
                cc.add((CurtidaComentario) obj);
            flag[2] = false;
        }

        @Override
        public void falha() {
            flag[2] = false;
        }
    });

    return null;

}

The only objects that can never be null are the "c" and the "u" the other two can.

I need "c" to be loaded so I can load the other three because I need your code.

I tried to do a while to stay until they ended up using the variable flag [], but it does not work and sometimes does not even execute the task.

    
asked by anonymous 23.10.2016 / 14:04

1 answer

1

The fact that both the trazer() and listar() method receives a Callback gives an idea that they are asynchronous.

If so, you do not need to use AsyncTask .

As you need the first object to "bring in" the second, what you should do is "bring" the second in the Callback method of the first.

Anything like this:

new CrtlComentario(contexto).trazer(post.getCodigo(), new CallbackTrazer() {
    @Override
    public void resultadoTrazer(Object obj) {
        c = (Comentario) obj;

        //*** Talvez colocar em um método **************

        new CrtlUsuario(contexto).trazer(c.getUsuarioPost(), new CallbackTrazer() {
            @Override
            public void resultadoTrazer(Object obj) {
                u = (Usuario) obj;

            }

            @Override
            public void falha() {
                //Tratar a falha
            }
        });

        //*********************
    }

    @Override
    public void falha() {
        //Tratar a falha
    }

});
    
23.10.2016 / 15:18