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

标签 android retrofit repository-pattern android-livedata

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

相关文章:

c# - 需要有关 ASP.NET MVC 3 体系结构的一些指导

java - 使用 Y 轴时间创建 AChartEngine TimeChart

fragment 中的 Android Google Maps V2

android - 在 Android 上使用 RTC 闹钟时允许手机休眠

android - 带过滤器的环回android sdk REST api

android - java.lang.IllegalArgumentException : must not have replace block. 对于动态查询参数使用@Query

.net - Asp Net Mvc 中的 SOLID 原理、Repository 模式和 EntityFramework 缓存

android - 获取 RecyclerView 中的可见项目

android - 为特定调用设置超时

orm - 工作单元和存储库模式的实际使用