How to make retrofit API call using ViewModel and LiveData

前端 未结 2 1673
温柔的废话
温柔的废话 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

    0 讨论(0)
  • 2020-12-28 16:50

    There are 3 problems in your code.

    1. You must create a MutableLiveData object because you have an empty response before API call then your LiveData object will be filled somehow through the IGDB response.
    private MutableLiveData<List<Game>> mGameList = new MutableLiveData();
    //...
    public LiveData<List<Game>> getGameList() {
        return mGameList;
    }
    
    1. Another mistake is changing the reference of mGameList instead of setting its value, So try to change:
    Timber.d("Call response body not null");
    mGameList = response.body();
    

    to

    mGameList.setValue(response.body());
    
    1. Calling retrofit inside your ViewModel class is avoiding separation of concerns. It's better to create a repository module and get your response through an interface. Read this article for details.

    Repository modules are responsible for handling data operations. They provide a clean API to the rest of the app. They know where to get the data from and what API calls to make when data is updated. You can consider them as mediators between different data sources (persistent model, web service, cache, etc.).

    0 讨论(0)
提交回复
热议问题