Como fazer uma chamada à API de modernização usando o ViewModel e o LiveData
é a primeira vez que estou tentando implementar a arquitetura MVVM e estou um pouco confuso sobre a maneira correta de fazer uma chamada de API.
Atualmente, estou apenas tentando fazer uma consulta simples a partir da API IGDB e gerar o nome do primeiro item em um log.
Minha atividade é configurada da seguinte forma:
public class PopularGamesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popular_games);
PopularGamesViewModel popViewModel = ViewModelProviders.of(this).get(PopularGamesViewModel.class);
popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
@Override
public void onChanged(@Nullable List<Game> gameList) {
String firstName = gameList.get(0).getName();
Timber.d(firstName);
}
});
}
}
O My View Model está configurado da seguinte forma:
public class PopularGamesViewModel extends AndroidViewModel {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
private LiveData<List<Game>> mGameList;
public PopularGamesViewModel(@NonNull Application application) {
super(application);
// Create the retrofit builder
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(igdbBaseUrl)
.addConverterFactory(GsonConverterFactory.create());
// Build retrofit
Retrofit retrofit = builder.build();
// Create the retrofit client
RetrofitClient client = retrofit.create(RetrofitClient.class);
Call<LiveData<List<Game>>> call = client.getGame(FIELDS,
ORDER,
LIMIT);
call.enqueue(new Callback<LiveData<List<Game>>>() {
@Override
public void onResponse(Call<LiveData<List<Game>>> call, Response<LiveData<List<Game>>> response) {
if (response.body() != null) {
Timber.d("Call response body not null");
mGameList = response.body();
} else {
Timber.d("Call response body is null");
}
}
@Override
public void onFailure(Call<LiveData<List<Game>>> call, Throwable t) {
Timber.d("Retrofit call failed");
}
});
}
public LiveData<List<Game>> getGameList() {
return mGameList;
}
Agora, o problema é que se trata de uma chamada de API, o valor inicial demGameList
será nulo, atécall.enqueue
retorna com um valor. Isso causará uma exceção de ponteiro nulo com
popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
Então, qual é a maneira correta de lidar com a observação de um LiveData enquanto a API está sendo feita?Eu executei a chamada da API de atualização no lugar certo?