作者:用途回家 | 来源:互联网 | 2022-11-28 20:39
1> Knossos..:
问题是fetchUser LiveData<>
每次调用都会创建一个新的。
这意味着您的第一个将永远不会收到更新。
请看看这些...
资料库
public class UserRepository {
private ApiService apiService;
private static UserRepository userRepository;
private UserRepository() {
apiService = RestClient.getClient().create(ApiService.class);
}
public synchronized static UserRepository getInstance() {
if (userRepository == null) userRepository = new UserRepository();
return userRepository;
}
// Your example code
public LiveData fetchUser() {
// Your problem lies here. Every time you fetch user data, you create a new LiveData.
// Instead, fetch user should update the data on a pre-existing LiveData.
final MutableLiveData data = new MutableLiveData<>();
Call call = apiService.getUser();
call.enqueue(new Callback() {
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
if (response.body() != null) {
data.postValue(response.body());
}
}
@Override
public void onFailure(@NonNull Call call, @NonNull Throwable t) {
data.postValue(null);
t.printStackTrace();
}
});
return data;
}
// My alterations below:
private MutableLiveData userLiveData = new MutableLiveData<>();
public LiveData getUser() {
return userLiveData;
}
public LiveData fetchUser2() {
Call call = apiService.getUser();
call.enqueue(new Callback() {
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
if (response.body() != null) {
userLiveData.postValue(response.body());
}
// TODO: Consider a fallback response to the LiveData here, in the case that bad data is returned. Perhaps null?
}
@Override
public void onFailure(@NonNull Call call, @NonNull Throwable t) {
userLiveData.postValue(null);
t.printStackTrace();
}
});
return userLiveData;
}
}
视图模型
我也会对此稍作更改。与其观察获取,不如直接观察LiveData。
user = UserRepository.getInstance().getUser();
以后,您可以随时从服务器请求更新的数据。
UserRepository.getInstance().fetchUser2();
您也可以调用fetchUser2()
的第一个构造UserRepository
。然后,只有更新会fetchUser2()
直接调用。
private UserRepository() {
apiService = RestClient.getClient().create(ApiService.class);
fetchUser2();
}
分段
另外,在您的片段中,请勿观察this
。改为使用getViewLifecycleOwner()
userViewModel.getUser().observe(getViewLifecycleOwner(), new Observer() {
@Override
public void onChanged(User user) {
//Set UI
}
});