Fetch API trên android java

Xin chào, em làm app android java lấy data từ API của webservice nhưng vấn đề phát sinh là giao diện load trước còn data fetch về sau (mạng lag, server yếu, …) thì làm sao để update lại giao diện khi data đã response về (ví dụ dùng retrofit). Bên react thì dùng lifecycle (componentDidMount) hoặc useEffect() Hook để update lại state khi đã fetch xong. Ban đầu data là mảng rỗng thì giao diện cho hiện icon loading, đến khi fetch xong thì cho update lại giao diện. Em cảm ơn!

Mọi người giải thích cơ chế giúp em với

Cậu hoàn toàn có thể setup callback từ retrofit khi nhận được response. Ở method callback đó, cậu cập nhật lại activity/component mà cậu muốn. Cậu cũng có thể trừu tượng hóa toàn bộ quá trình này trong 1 class listener nào đó:

public class OnApiResponseListener {
  private List<UpdatableComponent> components;

  // setter, getter, constructor...
  public void subscribe(UpdatableComponent component) {
     components.add(component);
  }
  public void onUpdate(Response response) {
    components.stream().forEach(component -> component.onUpdate(response));
  }
}
...
public interface UpdatableComponent {
    public void onUpdate(Response response);
}
...

public class SomeActivity extends Activity implements UpdatableComponent {
  ...
  // subscribe the listener 
  ...
  @Override
  public void onUpdate(Response response) {
    // Implement goes here
  }
}

Tớ không familiar lắm với React, cơ mà tớ nghĩ componentDidMount hay effect hook đều hoạt động tương tự vậy.

See also:

4 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?