Last active
August 26, 2018 12:54
-
-
Save ashishrawat2911/a52a185e2076f8661c3bb47f9e593027 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PhotographersViewModel extends ViewModel { | |
//this is the data that we will fetch asynchronously | |
private MutableLiveData<List<Photographer>> photographerList; | |
//we will call this method to get the data | |
public LiveData<List<Photographer>> getPhotographer() { | |
//if the list is null | |
if (photographerList == null) { | |
photographerList = new MutableLiveData<List<Photographer>>(); | |
//we will load it asynchronously from server in this method | |
loadPhotographers(); | |
} | |
//finally we will return the list | |
return photographerList; | |
} | |
//This method is using Retrofit to get the JSON data from URL | |
private void loadPhotographers() { | |
Retrofit retrofit = new Retrofit.Builder() | |
.baseUrl(Api.BASE_URL) | |
.addConverterFactory(GsonConverterFactory.create()) | |
.build(); | |
Api api = retrofit.create(Api.class); | |
Call<List<Photographer>> call = api.getPhotographer(); | |
call.enqueue(new Callback<List<Photographer>>() { | |
@Override | |
public void onResponse(Call<List<Photographer>> call, Response<List<Photographer>> response) { | |
//finally we are setting the list to our MutableLiveData | |
photographerList.setValue(response.body()); | |
} | |
@Override | |
public void onFailure(Call<List<Photographer>> call, Throwable t) { | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment