一、思路
ViewModel作为View监听器和View进行绑定,LiveData数据存放在ViewModel数据持久化,并具有观察性。View通过监听LiveData的数据变化,进行相应的UI操作。
UserRepository作为数据来源层,可以是本地数据库SqlLite,本地文件,网络数据
二、核心代码
- 1、ViewModel
package com.example.viewmodel_livedata.viewmodel;
import com.example.viewmodel_livedata.bean.LoginBean;
import com.example.viewmodel_livedata.repository.UserRepository;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.ViewModel;
public class UserViewModel extends ViewModel {
public MediatorLiveData<LoginBean> liveData = new MediatorLiveData<>();
private UserRepository userRepository = new UserRepository();
/**
* 请求登录
*
* @param userName
* @param pwd
*/
public void requestLogin(String userName, String pwd) {
liveData.setValue(userRepository.execueLogin(userName, pwd));
}
}
- 2、Repository
package com.example.viewmodel_livedata.repository;
import com.example.viewmodel_livedata.bean.LoginBean;
public class UserRepository {
/**
* 模拟 服务器登录
* @param userName
* @param pwd
* @return
*/
public LoginBean execueLogin(String userName, String pwd) {
if ("123".equals(userName) && pwd.equals("456")) {
return new LoginBean(200, " 登录成功");
} else {
return new LoginBean(400, " 登录失败");
}
}
}
- 3、View
package com.example.viewmodel_livedata;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.viewmodel_livedata.bean.LoginBean;
import com.example.viewmodel_livedata.viewmodel.UserViewModel;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
public class MainActivity extends AppCompatActivity {
private UserViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = ViewModelProviders.of(this).get(UserViewModel.class);
viewModel.liveData.observe(this, new Observer<LoginBean>() {
@Override
public void onChanged(LoginBean loginBean) {
Toast.makeText(MainActivity.this, loginBean.toString(), Toast.LENGTH_LONG).show();
}
});
}
public void login(View view) {
viewModel.requestLogin("123","4567");
}
}
网友评论