Google Jetpack MVVM架构设计
View绑定到ViewModel,然后执行一些命令在向它请求一个动作。而反过来,ViewModel跟Model通讯,告诉它更新来响应UI。
示例:协程+Retrofit+ViewModel+LiveData+DataBinding网络通信
准备工作:
启用DataBing
在module的gradle添加kotlin-kapt
插件
plugins {
...
id 'kotlin-kapt'
}
在android下添加DataBinding的支持
android {
...
// 添加DataBinding的支持 必须有 kapt
dataBinding {
enabled = true
}
}
1、Model层
data class LoginRegisterResponse(
val admin: Boolean,
val chapterTops: List<*>,
val collectIds: List<*>,
val email: String?,
val icon: String?,
val id: String?,
val nickname: String?,
val password: String?,
val publicName: String?,
val token: String?,
val type: Int,
val username: String?
)
data class ResponseWrapper(val data: T, val errorCOde: Int, val errorMsg: String)
2、Api
interface WanAndroidApi {
@POST("/user/login")
@FormUrlEncoded
suspend fun loginActionCoroutine(
@Field("username") username: String,
@Field("password") password: String
): ResponseWrapper
}
class ApiClient {
private object Holder {
//单例
val INSTANCE = ApiClient()
}
companion object {
val instance = Holder.INSTANCE
}
fun instanceRetrofit(apiInterface: Class): T {
val mOkHttpClient = OkHttpClient().newBuilder().apply {
readTimeout(10000, TimeUnit.SECONDS)
connectTimeout(10000, TimeUnit.SECONDS)
writeTimeout(10000, TimeUnit.SECONDS)
}.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://www.wanandroid.com")
.client(mOkHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(apiInterface)
}
}
3、Repository仓库
主要逻辑可以放在Repository来做。
class ApiRepository {
suspend fun requestLogin(
username: String,
password: String
): ResponseWrapper {
if (username.isEmpty() || password.isEmpty()) {
Log.d("login", "账号或密码不能为空")
}
// TODO: 2022/1/14 其他逻辑 放在Repository里做,不要放在ViewModel里做
return ApiClient.instance.instanceRetrofit(WanAndroidApi::class.java)
.loginActionCoroutine(username, password)
}
}
4、VideModel
/**
* 1、ViewModel的职责:只做一件事,就是管理所有的LiveData数据状态的稳定性,其他的逻辑不能放在这里
* 2、ViewModel是通过ViewModelProvider.NewInstanceFactory()工厂方法创建的,如果VideModel里有大量逻辑,会影响VideModel的创建速度
*/
class ApiViewModel : ViewModel() {
//DataBinding将userLiveData和布局绑定,只要userLiveData有变化,就相当于更新了UI
var userLiveData = MutableLiveData>()
fun requestLogin(username: String, password: String) {
//GlobalScope是全局的,不能使用,Activity销毁后GlobalScope也不会销毁,会造成内存泄漏
//这里需要使用viewModelScope ,默认是主线程
viewModelScope.launch {
//=左边 userLiveData.value是在主线程中 右边ApiRepository().requestLogin(username, password)是在异步线程中
userLiveData.value = ApiRepository().requestLogin(username, password)
}
}
}
5、View层
class MvvmActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mvvm)
//绑定DataBinding
val binding =
DataBindingUtil.setContentView(this, R.layout.activity_mvvm)
binding.lifecycleOwner = this
//从这里可以看出,ViewModel是通过ViewModelProvider.NewInstanceFactory()工厂方法创建的,如果VideModel里有大量逻辑,会影响VideModel的创建速度
val viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(
ApiViewModel::class.java
)
binding.apiVM = viewModel
button.setOnClickListener {
viewModel.requestLogin("Derry-vip", "123456")
}
}
}
关注木水小站 (zhangmushui.cn)和微信公众号【木水Code】,及时获取更多最新技术干货。