【发布时间】:2019-07-26 00:12:07
【问题描述】:
尝试使用改造调用我的 API 并更新模型。它正确初始化并且能够提取数据,但是当我通过按下更新按钮手动触发它时,onChange QuestionResponse 模型为空。这似乎是一种竞争条件,因为在调试时它会在调用 onResponse 之前触发 onChange。我尝试从 setValue 更改为 postvalue 等。
活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewModel = ViewModelProviders.of(this).get(BasicViewModel.class);
mViewModel.getQuestions().observe(this, new Observer<QuestionResponse>() {
@Override
public void onChanged(QuestionResponse response) {
QuestionResponse temp = mViewModel.getQuestions().getValue();
Toast.makeText(MainActivity.this, "Questions Updated", Toast.LENGTH_SHORT).show();
}
});
updateButton = findViewById(R.id.updateButton);
updateButton .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update();
}
});
}
private void update(){
mViewModel.updateQuestions();
}
查看模型
private Repository repository;
private Application application;
private MutableLiveData<QuestionResponse> questionMutableLiveData;
public BasicViewModel(Application application){
super(application);
this.application = application;
repository = new Repository();
questionMutableLiveData = repository.getQuotes();
}
public void updateQuestions(){
questionMutableLiveData.setValue(repository.getQuotes().getValue());
}
public LiveData<QuestionResponse> getQuestions(){
if(questionMutableLiveData == null){
System.out.println("Something Is Wrong");
}
return questionMutableLiveData;
}
改装服务
public class Repository {
MutableLiveData<QuestionResponse> questionData;
ApiService apiService;
public QuoteMRepository(){
apiService = RetrofitSingleton.getRetrofitInstance().create(ApiService.class);
}
public MutableLiveData<QuestionResponse> getQuotes(){
Call<QuestionResponse> call = apiService.getQuestions();
//Old version of doing it
//MutableLiveData<QuestionResponse> questionData = new MutableLiveData<>();
//New version, seems to be working but triggering twice
if(questionData == null) {
questionData = new MutableLiveData<>();
}
call.enqueue(new Callback<QuestionResponse>() {
@Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
if(response.isSuccessful()){
QuestionResponse reply = response.body();
questionData.setValue(reply);
}
}
@Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
System.out.println("Failure");
}
});
return questionData;
}
}
【问题讨论】:
标签: android retrofit2 android-mvvm