Last active
June 10, 2018 20:08
-
-
Save dimanem/ab67a6c0f55129482793258aab1477ec 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 MyAPI { | |
@GET("{path}") | |
Call<List<Data>> getData(@Path("path") String pathValue); | |
} | |
public class Repo { | |
private Context _context; | |
private List<Data> _loadedData; | |
private MyRetrofitService _retrofitService; | |
// Not sure you need context! | |
public Repo(Context context) { | |
_context = context; | |
// implementation 'com.google.code.gson:gson:2.8.2' | |
// implementation 'com.squareup.retrofit2:retrofit:2.3.0' | |
// implementation 'com.squareup.retrofit2:converter-gson:2.3.0' | |
Retrofit retrofit = new Retrofit.Builder() | |
.baseUrl("https://<your base url>") | |
.addConverterFactory(GsonConverterFactory.create()) | |
.build(); | |
_retrofitService = retrofit.create(MyAPI.class); | |
} | |
public void getData(String input, MyCallback myCallback) { | |
if (loadedData != null) { // use local data | |
loadData(_loadedData, input, callback); | |
} else { // load data from network | |
retrofit.getData(new Callback { | |
void onResponse(Response response) { | |
// Save to local | |
_loadedData = _retrofitService.getData(); | |
Call <List<SponsorsResult>> call = service.getData(); | |
call.enqueue(new Callback<List<Data>>() { | |
@Override | |
public void onResponse(Call<List<Data>> call, Response<List<Data>> response) { | |
List<Data> data = response.body(); | |
_loadedData = data; | |
loadData(_loadedData, input, myCallback); | |
} | |
@Override | |
public void onFailure(Call<List<Data>> call, Throwable t) { | |
myCallback.onError("Print t") | |
} | |
}); | |
} | |
} | |
private void loadData(List<Data> data, String input, MyCallback myCallback) { | |
String parsedInput = parseInput(data, input); | |
if (parseInput == null) { | |
callback.onError("Invalid input"); | |
} else { | |
String result = fetchResult(data, input); | |
callback.onSuccess(parsedInput, result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment