Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Last active September 3, 2016 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zhuinden/29f31517f9593c8f08dea394c772f271 to your computer and use it in GitHub Desktop.
Save Zhuinden/29f31517f9593c8f08dea394c772f271 to your computer and use it in GitHub Desktop.
Realm background operation with Retrofit2 in AsyncTask
public class GetNewsPostAsyncTask
extends AsyncTask<Void, Void, Void> {
private Retrofit retrofit;
private ApiService apiService;
private long postId;
public GetNewsPostAsyncTask(Retrofit retrofit, ApiService apiService, long postId) {
this.retrofit = retrofit;
this.apiService = apiService;
this.postId = postId;
}
@Override
protected Void doInBackground(Void... voids) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance(); // NOT RealmManager.getRealm()!
Call<NewsPost> postCall = apiService.downloadPost(postId);
Response<NewsPost> response = postCall.execute(); // sync download
if(handleRetrofitError(retrofit, response)) {
// error occurred, do something with error
return null;
}
final NewsPost newsPost = response.body();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.insertOrUpdate(newsPost);
// assuming you can directly use RealmObject as JSON class
// typically I map between a dedicated JSON class and a RealmObject
// so that would mean `realm.insertOrUpdate(mapper.toRealm(newsPostJSON));`
}
});
} finally {
if(realm != null) {
realm.close(); // ALWAYS CLOSE the background Realm
}
}
return null; // NO NEED FOR `onPostExecute()`, the RealmChangeListener handles it automatically!
}
public boolean handleRetrofitError(Retrofit retrofit, Response<?> response) {
// beautiful retrofit2 error handling
if(response == null) {
// do something with failure
return true;
}
if(response != null && !response.isSuccessful() && response.errorBody() != null) {
Converter<ResponseBody, ErrorResponse> converter = retrofit.responseBodyConverter(ErrorResponse.class,
new Annotation[0]); // <3 that empty array
try {
ErrorResponse errorResponse = converter.convert(response.errorBody());
// do something with error
} catch(IOException e) {
// do something with failure
}
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment