TLDR:如何使用 LiveData 正确实现 MVVM 架构?
我有一个观察 viewModel 暴露的 livedata 的片段类:
viewModel.loginResultLiveData.observe
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private val viewModel by fragmentScopedViewModel { injector.loginViewModel }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentLoginBinding.inflate(inflater, container, false)
val username = binding.loginInputField.toString()
val password = binding.passwordInputField.toString()
binding.loginSignInButton.setOnClickListener { viewModel.login(
username,
password
) }
viewModel.loginResultLiveData.observe(viewLifecycleOwner){
when(it){
is LoginResult.Success -> doSmth()
}
}
return binding.root
}
}
视图模型类只要求一个映射的 livedata 对象。
class LoginViewModel @Inject internal constructor(
private val loginUseCase: LoginUseCase
) : ViewModel() {
lateinit var loginResultLiveData: MutableLiveData<LoginResult>
fun login(username: String, password: String) {
loginResultLiveData = loginUseCase.login(username, password)
}
}
模型使用用例来映射原始格式的结果,也会映射错误:
class LoginUseCase @Inject internal constructor(
private val authRepository: AuthEmailRepository
) {
var loginResultLiveData = MutableLiveData<LoginResult>()
fun login(userName: String, password: String): MutableLiveData<LoginResult> {
authRepository.login(userName, password)
.addOnCompleteListener {
if (it.isSuccessful) {
loginResultLiveData.postValue(LoginResult.Success)
} else {
loginResultLiveData.postValue(LoginResult.Fail(it.exception.toString()))
}
}
return loginResultLiveData
}
}
问题是只有在loginSignInButton
点击之后,模型才会创建一个 liveData 对象。但是我在设置 onClickListener 后立即开始观察这个对象。此外,每次单击按钮时,都会创建一个新的 实例viewModel.loginResultLiveData
,这是没有意义的。
binding.loginSignInButton.setOnClickListener { viewModel.login(
username,
password
) }
viewModel.loginResultLiveData.observe(viewLifecycleOwner){
when(it){
is LoginResult.Success -> doSmth()
}
}
在这种情况下,如何使用 LiveData 正确实现 MVVM 架构?
我还可以将我现在拥有的逻辑移动LoginUseCase
到 ModelView 中,然后使用类似的东西,这样可以避免前面描述的问题。但是我不能将映射/错误处理委托给用例。
class LoginViewModel @Inject internal constructor(
private val loginUseCase: LoginUseCase
) : ViewModel() {
val loginResult: MutableLiveData<LoginResult> = MutableLiveData()
fun login(username: String, password: String) = loginUseCase.login(username, password)
.addOnCompleteListener {
if (it.isSuccessful) {
loginResult.postValue(LoginResult.Success)
} else {
loginResult.postValue(LoginResult.Fail(it.exception.toString()))
}
}
}