Cómo hacer una llamada de API de modificación usando ViewModel y LiveData
esta es la primera vez que intento implementar la arquitectura MVVM, y estoy un poco confundido acerca de la forma correcta de hacer una llamada API.
Actualmente, solo estoy tratando de hacer una consulta simple desde la API IGDB, y mostrar el nombre del primer elemento en un registro.
Mi actividad se configura de la siguiente manera:
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);
}
});
}
}
Mi modelo de vista se configura de la siguiente manera:
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;
}
Ahora el problema es porque esta es una llamada a la API, el valor inicial demGameList
será nulo, hasta quecall.enqueue
regresa con un valor. Esto provocará una excepción de puntero nulo con
popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
Entonces, ¿cuál es la forma correcta de manejar la observación de un LiveData, mientras se realiza una llamada API? ¿Realicé la llamada de API Retrofit en el lugar correcto?