简体   繁体   English

LiveData最初不显示数据

[英]LiveData doesn't show data initially

I'm fetching some data from my server and observing it using LiveData. 我正在从服务器中获取一些数据,并使用LiveData对其进行观察。 When my fragment starts initially, it doesn't return anything in onChanged() , and after switching fragment, it triggers onChanged() with right data. 当我的片段最初开始时,它不会在onChanged()返回任何内容,并且在切换片段之后,它将使用正确的数据触发onChanged()

After debugging, I saw that my API call is successful and I get data there, but it is not returning data through onChanged() initially. 调试之后,我看到我的API调用成功,并且在那里获取了数据,但最初并没有通过onChanged()返回数据。

Repository: 库:

public class UserRepository {
    private ApiService apiService;
    private static UserRepository repository;
    private MutableLiveData<User> user = new MutableLiveData<>();

    private UserRepository() {
        apiService = RestClient.getClient().create(ApiService.class);
    }

    public synchronized static UserRepository getInstance() {
        if (repository == null) repository = new UserRepository();
        return repository;
    }

    public LiveData<User> getUser() {
        return user;
    }

    public void fetchUser() {
        Call<User> call = apiService.getUser();
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(@NonNull Call<User> call, @NonNull Response<User> response) {
                if (response.body() != null) user.postValue(response.body());
            }

            @Override
            public void onFailure(@NonNull Call<User> call, @NonNull Throwable t) {
                user.postValue(null);
                t.printStackTrace();
            }
        });
    }
}

ViewModel: 视图模型:

public class UserViewModel extends AndroidViewModel {
    private LiveData<User> user;

    public UserViewModel(@NonNull Application application) {
        super(application);
        user = UserRepository.getInstance().getUser();
    }

    public LiveData<User> getUser() {
        return user;
    }
}

Fragment: 分段:

userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
userViewModel.getUser.observe(this, user -> {
    //Set data
})

I can solve this problem by calling UserRepository.getInstance().getUser() before observing in my fragment. 我可以通过在观察片段之前调用UserRepository.getInstance().getUser()来解决此问题。 But that is not the preferred method as said by Google, and kind of a workaround. 但这不是Google所说的首选方法,并且是一种解决方法。

As already mentioned in the comments, you seem to call getUser() on the repository before you even set any value in fetchUser(). 正如评论中已经提到的,您似乎甚至在fetchUser()中设置任何值之前都在存储库上调用getUser()。 Change fetchUser() so that it returns LiveData and then call that method from the view model instead of getUser(): 更改fetchUser()使其返回LiveData,然后从视图模型而不是getUser()调用该方法:

public LiveData<User> fetchUser() {
    Call<User> call = apiService.getUser();
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(@NonNull Call<User> call, @NonNull Response<User> response) {
            if (response.body() != null) user.postValue(response.body());
        }

        @Override
        public void onFailure(@NonNull Call<User> call, @NonNull Throwable t) {
            user.postValue(null);
            t.printStackTrace();
        }
    });

    return user;
 }

And then in the view model: 然后在视图模型中:

public UserViewModel(@NonNull Application application) {
    super(application);
    user = UserRepository.getInstance().fetchUser();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM