在Android中使用翻新,MVVM,LiveData的登录示例 [英] Login Example using Retrofit, MVVM, LiveData in android

查看:70
本文介绍了在Android中使用翻新,MVVM,LiveData的登录示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了文章,但是观察到MainActivity中的响应变化.

I checked this article but observe the response changes in MainActivity.

这是我的 LoginRepo

public MutableLiveData<LoginResponseModel> checkLogin(LoginRequestModel loginRequestModel) {
    final MutableLiveData<LoginResponseModel> data = new MutableLiveData<>();
    Map<String, String> params = new HashMap<>();
    params.put("email", loginRequestModel.getEmail());
    params.put("password", loginRequestModel.getPassword());
    apiService.checkLogin(params)
            .enqueue(new Callback<LoginResponseModel>() {
                @Override
                public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
                    if (response.isSuccessful()) {
                        data.setValue(response.body());
                        Log.i("Response ", response.body().getMessage());
                    }
                }

                @Override
                public void onFailure(Call<LoginResponseModel> call, Throwable t) {
                    data.setValue(null);
                }
            });
    return data;
}

这是我的代码 LoginViewModel

public class LoginViewModel extends ViewModel {


public MutableLiveData<String> emailAddress = new MutableLiveData<>();
public MutableLiveData<String> password = new MutableLiveData<>();
Map<String, String> params = new HashMap<>();
LoginRepo loginRepo;

private MutableLiveData<LoginResponseModel> loginResponseModelMutableLiveData;


public LiveData<LoginResponseModel> getUser() {
    if (loginResponseModelMutableLiveData == null) {
        loginResponseModelMutableLiveData = new MutableLiveData<>();
        loginRepo = LoginRepo.getInstance();
    }

    return loginResponseModelMutableLiveData;
}


//This method is using Retrofit to get the JSON data from URL
private void checkLogin(LoginRequestModel loginRequestModel) {
    loginResponseModelMutableLiveData = loginRepo.checkLogin(loginRequestModel);
}

public void onLoginClick(View view) {
    LoginRequestModel loginRequestModel = new LoginRequestModel();
    loginRequestModel.setEmail(emailAddress.getValue());
    loginRequestModel.setPassword(password.getValue());
    params.put("email", loginRequestModel.getEmail());
    params.put("password", loginRequestModel.getPassword());
    checkLogin(loginRequestModel);
}

}

这是我 LoginActivity

 private LoginViewModel loginViewModel;
private ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
    binding = DataBindingUtil.setContentView(LoginActivity.this, R.layout.activity_main);
    binding.setLifecycleOwner(this);
    binding.setLoginViewModel(loginViewModel);
    loginViewModel.getUser().observe(this, new Observer<LoginResponseModel>() {
        @Override
        public void onChanged(@Nullable LoginResponseModel loginUser) {
            if (loginUser != null) {
                binding.lblEmailAnswer.setText(loginUser.getUser().getId());
                Toast.makeText(getApplicationContext(), loginUser.getUser().getId(), Toast.LENGTH_SHORT).show();
            }

        }
    });

}

LoginViewModel中使用的

onLoginClick方法正在使用LiveData.

onLoginClick method used in LoginViewModel is using LiveData.

来自api的响应是可以的.但是未显示onchange(),如何在简单的登录示例中使用MVVM模式使用LiveData.请帮忙!

The Response coming from api is okay. But onchange() it is not shown, how to use LiveData using MVVM pattern in simple Login Example. Please help!

推荐答案

这是我尝试使用您的类的方法,只是将改型更改为后台线程以等待5秒,然后设置数据(您需要确认响应是否成功)因为您不会在失败时不更改数据,因此如果loginResponseModel为null,则它将输入onChanged方法,但不会执行任何操作,因为如果它等于null,则没有条件.我做到了

Here is what i have tried using your classes just altering retrofit to background thread to wait 5 seconds and then setting the data (you need to confirm the response being successful as you don't change the data if it's failing and hence if the loginResponseModel is null then it will enter the onChanged Method but it won't do anything as you don't have a condition if it is equals to null) here is what i did

在Main Activity-> onCreate()中,我刚刚创建了viewmodel并在mutableLiveData上进行了观察

in Main Activity -> onCreate() i just created the viewmodel and observed on the mutableLiveData

myViewModel.onLoginClick(null);
        myViewModel.simpleModelMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if(s==null)
                  Log.v("testinggg","test - onChanged --- Null " );
                else
                    Log.v("testinggg","test - onChanged --- s -> "+s );
            }
        });

然后是ViewModel->,其中您将把MutableLiveData本身命名为simpleModelMutableLiveData

Then here is the ViewModel -> in which you will have the MutableLiveData itself named simpleModelMutableLiveData

     MutableLiveData<String> simpleModelMutableLiveData;


    public LiveData<String> getUser() {
        if (simpleModelMutableLiveData == null) {
            simpleModelMutableLiveData = new MutableLiveData<>();

        }

        return simpleModelMutableLiveData;
    }

  // this method will return Object of MutableLiveData<String> and let the simpleModelMutableLiveData be the returned object
    private void checkLogin(String placeholder) {
        simpleModelMutableLiveData = MyRepo.checkLogin(placeholder);
    }

    public void onLoginClick(View view) {

        checkLogin("test");
    }

,最后是Repo方法,在该方法中,我将返回MutableLiveData并让simpleModelMutableLiveData作为返回值,并使用runnable启动一个后台线程,该线程将等待5秒钟,然后再使用处理程序设置该值(在您的情况下,您将入队后需要在重写方法onResponse和onFailure中设置数据的值)

and at last the Repo method in which i will return the MutableLiveData and let the simpleModelMutableLiveData to be the return and initiate a background thread using runnable that will wait 5 seconds before it sets the value using a handler (in your case you will need to set the value of the data after enqueue inside the Overridden Methods onResponse and onFailure)

如下

public static MutableLiveData<String> checkLogin(String test) {
        final MutableLiveData<String> data = new MutableLiveData<>();


        Runnable r = new Runnable() {
            public void run() {
                runYourBackgroundTaskHere(data);
            }
        };

        new Thread(r).start();



        return data;
    }

     private static void runYourBackgroundTaskHere(final MutableLiveData<String> data) {

        try {
            Thread.sleep(5000);
//            Handler handler  = new Handler();
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // things to do on the main thread

                /* Here i set the data to sss and then null and when 
                   you check the logcat and type the keyword used for 
                   logging which is "testinggg" 
                   you will find it show sss and then null which means 
                   it has entered the onChanged and showed you the log */

                    data.setValue("sss"); 
                    data.setValue(null);
                }
            });

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

这篇关于在Android中使用翻新,MVVM,LiveData的登录示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆