android - отправлять комментарии на сервер одновременно и загружать их в RecyclerView - PullRequest
1 голос
/ 20 апреля 2020

Я отправляю комментарии на сервер с двумя устройствами одновременно. Позже я добавлю их в список RecyclerView. Но иногда один из комментариев не отображается. Код:

private void makeComment(String comment) {

    Call<Model> call = restApiClass.commentPost(user_id, post_id, comment, date);
    call.enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Call<Model> call, Response<Model> response) {

            if (response.body().isSuccess()) {
                //send a comment and later refresh the RecylerView to get new added comment.
                getComments();
            } 
    }

 private void getComments() {

    Call<List<CommentsModel>> call = restApiClass.getCommentsPost(post_id);
    call.enqueue(new Callback<List<CommentsModel>>() {
        @Override
        public void onResponse(Call<List<CommentsModel>> call, Response<List<CommentsModel>> response) {

            if (response.isSuccessful()) {

                    list = response.body();
                    if (commentsAdapter == null) {
                        commentsAdapter = new CommentsAdapter(list, getContext());
                        commentsRecyclerView.setAdapter(commentsAdapter );
                    }
                    //if there are already comments in Adapter don't create again
                    else {

                        commentsAdapter.addComment(list.get(list.size() - 1));
                        //go to last index of RecyclerView:
                        ((LinearLayoutManager) commentsPostRecyclerView.getLayoutManager()).
                                scrollToPositionWithOffset(list.size() - 1, 0);
                    }
             }

addComment () в комментариях Адаптер:

 public void addComment(CommentsModel comment) {
    this.list.add(comment);
    notifyItemInserted(this.list.size()-1); //item is added to last position.
}
...