Android-具有LiveData组件的MVVM和存储库中的Retrofit调用

rma*_*aix 8 android repository-pattern retrofit android-livedata

我想将以下组件用于身份验证视图(登录):

  • MVVM
  • 实时数据
  • 翻新
  • 资料库

我不知道如何才能在Repository类中收到对当前ViewModel的异步Retrofit调用。

查看-> ViewModel->带有LiveData的存储库。

有人会想到一个例子吗?

Jee*_*ede 6

您可以执行以下操作:

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
    })
}
}
Run Code Online (Sandbox Code Playgroud)

MyViewModel.kt

class MyViewModel : ViewModel() {

val liveData = MutableLiveData<Your response type here>()
val myRepository = MyRepository()

fun callApi() {
    myRepository.callMyRetrofitApi(liveData)
}
}
Run Code Online (Sandbox Code Playgroud)

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()
        }

    })
}
}
Run Code Online (Sandbox Code Playgroud)

尝试像这样进行设置。

希望能帮助到你 !