Last active
April 29, 2019 03:59
-
-
Save donrokzon/82bafd7a7641beb60cb08484bb811b08 to your computer and use it in GitHub Desktop.
ViewModel
This file contains hidden or 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
| viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class); | |
| viewModel.getResponse().observe(this, data -> { | |
| progressBar.setVisibility(View.GONE); | |
| init(data); | |
| }); | |
| viewModel.isNetworkAvailable.observe(this,data ->{ | |
| if (!data){ | |
| showSnackbar(); | |
| } | |
| }); | |
| public class MainActivityViewModel extends AndroidViewModel { | |
| private String TAG = "MainActivityViewModel"; | |
| private Gson gson = new Gson(); | |
| public MutableLiveData<Boolean> isNetworkAvailable =new MutableLiveData<>(); | |
| private MutableLiveData<List<Data>> stringMutableLiveData; | |
| public MainActivityViewModel(@NonNull Application application) { | |
| super(application); | |
| } | |
| LiveData<List<Data>> getResponse() { | |
| if (stringMutableLiveData == null) { | |
| stringMutableLiveData = new MutableLiveData<>(); | |
| callApi(); | |
| } | |
| return stringMutableLiveData; | |
| } | |
| public void callApi() { | |
| if (isNetworkAvailable()) { | |
| Log.i(TAG, "callApi: "); | |
| JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, | |
| Constants.URL, null, response -> { | |
| Log.i(TAG, "onResponse: "); | |
| NetworkResponse networkResponse = gson.fromJson(response.toString(), NetworkResponse.class); | |
| stringMutableLiveData.postValue(networkResponse.getData()); | |
| }, error -> { | |
| Log.i(TAG, "onErrorResponse: " + error.toString()); | |
| }); | |
| RequestQueue requestQueue = Volley.newRequestQueue(getApplication()); | |
| requestQueue.add(jsonObjReq); | |
| }else { | |
| isNetworkAvailable.postValue(false); | |
| } | |
| } | |
| private boolean isNetworkAvailable() { | |
| ConnectivityManager connectivityManager | |
| = (ConnectivityManager)getApplication(). getSystemService(Context.CONNECTIVITY_SERVICE); | |
| assert connectivityManager != null; | |
| NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); | |
| return activeNetworkInfo != null && activeNetworkInfo.isConnected(); | |
| } | |
| } | |
| implementation 'com.google.code.gson:gson:2.8.5' | |
| implementation 'com.squareup.picasso:picasso:2.71828' | |
| implementation 'com.android.volley:volley:1.1.1' | |
| // Lifecycle components | |
| implementation 'android.arch.lifecycle:extensions:1.1.1' | |
| annotationProcessor 'android.arch.lifecycle:compiler:1.1.1' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment