我在我的應用程序中使用Android Architecture Components
。在My Login Activty中,當登錄失敗時,我顯示一個對話框!實時數據被多次調用?
由於實時數據,該對話框已顯示3次以上。我加了一些日誌&發現livedata
被多次調用。
我該如何解決這個問題?
ACTIVITY
mViewModel.authenticate(token, binding.inputPassword.getText().toString()).observe(LoginActivity.this, apiResponse -> {
progress.dismiss();
if (apiResponse != null) {
if (apiResponse.getError() != null) {
Log.e("Login", "Network Failure");
} else {
if (apiResponse.getAuthuser().getStatus().equals("VALID")) {
PrefUtils.saveUserToPrefs(LoginActivity.this, apiResponse.getAuthuser());
finish();
} else if (apiResponse.getAuthuser().getStatus().equals("INVALID")) {
Log.e("LOGIN Issue ", "Showing Dialog" + apiResponse.getAuthuser().getStatus());
loginFailure();
}
}
}
});
視圖模型
class LoginActivityViewModel extends ViewModel {
private final FarmerRepository farmerRepository;
private MediatorLiveData<ApiResponse> mApiResponse;
LoginActivityViewModel(FarmerRepository repository) {
mApiResponse = new MediatorLiveData<>();
farmerRepository = repository;
}
MediatorLiveData<ApiResponse> authenticate(String encryptedMobile, String pwd) {
mApiResponse.addSource(
farmerRepository.authenticate(encryptedMobile, pwd),
apiResponse -> mApiResponse.setValue(apiResponse)
);
return mApiResponse;
}
}
logcat的
11-01 00:13:31.265 24386-24386 E/LOGIN Issue: Showing DialogINVALID
11-01 00:13:31.312 24386-24386 E/LOGIN Issue: Showing DialogINVALID
11-01 00:13:37.034 24386-24386 E/LOGIN Issue: Showing DialogINVALID
11-01 00:13:38.196 24386-24386 E/LOGIN Issue: Showing DialogINVALID
11-01 00:13:38.234 24386-24386 E/LOGIN Issue: Showing DialogINVALID
11-01 00:13:38.273 24386-24386 E/LOGIN Issue: Showing DialogINVALID
UPDATE
使用SingleLiveEvent後。它沒有被觀察到。你能告訴我代碼有什麼問題嗎?
更新視圖模型
class LoginActivityViewModel extends ViewModel {
private final FarmerRepository farmerRepository;
private MediatorLiveData<ApiResponse> mApiResponse;
private SingleLiveEvent<ApiResponse> mMsgUpdate;
LoginActivityViewModel(FarmerRepository repository) {
mApiResponse = new MediatorLiveData<>();
farmerRepository = repository;
mMsgUpdate = new SingleLiveEvent<>();
}
SingleLiveEvent<ApiResponse> authenticate(String encryptedMobile, String pwd) {
mApiResponse.addSource(
farmerRepository.authenticate(encryptedMobile, pwd),
apiResponse -> mMsgUpdate.setValue(apiResponse)
);
return mMsgUpdate;
}
}
這並不值得賞金,因爲這是LiveData的常見行爲。 https://github.com/googlesamples/android-architecture-components/issues/63 –
@EmanuelS你可以檢查更新嗎? – user3467240
添加多個來源不是應該在視圖模型中完成的工作。它應該在存儲庫中處理的工作 –