gpt4 book ai didi

Android - 带有 LiveData 组件的 MVVM 和 Repository 中的 Retrofit 调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:48:58 26 4
gpt4 key购买 nike

我想将以下组件用于身份验证 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com