我想在用户填写数据并按提交后将数据从存储库传递到viewModel:
查看模型:
public class LoginViewModel extends ViewModel {
private boolean isValid = true;
private MutableLiveData<Boolean> loadingListener;
private LoginRepository loginRepository;
public LoginViewModel() {
loginRepository = new LoginRepository();
loadingListener = new MutableLiveData<>();
}
public void onSubmitLoginClicked(LoginRequest loginRequest) {
if(loginValidation(loginRequest)) {
loginRequest.setToken(MyTools.getKey(MyApplication.getApplication(), "token"));
loginRepository.getLoginData(loginRequest);
loadingListener.setValue(true);
}
}
public LiveData<LoginResponse> getLoginViewModelResponseListener() {
return loginRepository.getLoginResponseListener();
}
存储库:
private MutableLiveData<LoginResponse> loginResponseListener;
public LoginRepository() {
loginResponseListener = new MutableLiveData<>();
}
public LiveData<LoginResponse> getLoginResponseListener() {
return loginResponseListener;
}
public void getLoginData(LoginRequest loginRequest) {
RetrofitClient.INSTANCE.callEndPoint().login(loginRequest).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if(response.body() != null) {
loginResponseListener.setValue(response.body());
Log.e(TAG, "onResponse: " + response.body().msg);
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e(TAG, "onFailure: "+ t.getMessage() );
}
});
}
[他们说用户Transformations.setMap,但我听不懂,我尝试使用它很多次,但没有找到结果。有人可以帮助我吗?
我被困在这里很多天..请帮助我:
1-如何将数据从存储库传递到viewModel2-如何检查数据是否为null或是否成功.. etc3-如何从视图模型中观察视图,但是在检查数据是否不为null后!4- Google编写的资源类是什么?我找不到关于它的Java代码我不明白,也无法实施这个:
sealed class Resource<T>(
val data: T? = null,
val message: String? = null
) {
class Success<T>(data: T) : Resource<T>(data)
class Loading<T>(data: T? = null) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
}
[请帮助我感到沮丧
ViewModel documentation说
ViewModel对象永远不能观察到生命周期感知的可观察对象的变化,例如LiveData对象。
在此博客中,您可以了解如何正确实现viewModel模式
https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54