How to make retrofit API call using ViewModel and LiveData

前端 未结 2 1672
温柔的废话
温柔的废话 2020-12-28 16:10

this is the first time I\'m trying to implement MVVM architecture, and I\'m a bit confused about the correct way to make an API call.

Currently, I\'m just trying to

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 16:32

    I just inspired by Google's Demo and created a library, which can add LiveData support for Retrofit. The usage is simple:

    Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(LiveDataCallAdapterFactory())
                .build()
                .create(GithubService::class.java)
                .getUser("shawnlinboy").observe(this,
                    Observer { response ->
                        when (response) {
                            is ApiSuccessResponse -> {
                              //success response
                            }
                            else -> {
                                //failed response
                            }
                        }
                    })
    

    The library site: https://github.com/shawnlinboy/retrofit-livedata-adapter

提交回复
热议问题