我想将以下组件用于身份验证 View (登录):
- MVVM
- 实时数据
- 改造
- 存储库
我不知道如何接收 Repository 类中对当前 ViewModel 的异步 Retrofit 调用。
View -> ViewModel -> Repository with LiveData。
有人会有想法或例子来实现这个吗?
最佳答案
你可以像下面这样:
YourActivity.kt
class YourActivity : AppCompatActivity() {
private val myViewModel by lazy {
return@lazy ViewModelProviders.of(this).get(MyViewModel::class.java) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onViewReady(savedInstanceState)
myViewModel.callApi() // You can do it anywhere, on button click etc..
observeResponseData() // observe it once in onCreate(), it'll respect your activity lifecycle
}
private fun observeResponseData() {
myViewModel.liveData.observe(this, Observer { data ->
// here will be your response
})
}
}
MyViewModel.kt
class MyViewModel : ViewModel() {
val liveData = MutableLiveData<Your response type here>()
val myRepository = MyRepository()
fun callApi() {
myRepository.callMyRetrofitApi(liveData)
}
}
MyRepository.kt
class MyRepository {
//Make your retrofit setup here
//This is the method that calls API using Retrofit
fun callMyRetrofitApi(liveData: MutableLiveData<Your response type here>) {
// Your Api Call with response callback
myRetrofitInstance.apiMethod.enqueue(object : Callback<Your response type here> {
override fun onFailure(call: Call<Your response type here>, t: Throwable) {
}
override fun onResponse(call: Call<Your response type here>, response: Response<Your response type here>) {
liveData.value = response.body()
}
})
}
}
尝试像这样进行设置。
希望对您有所帮助!
关于Android - 带有 LiveData 组件的 MVVM 和 Repository 中的 Retrofit 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52875104/