Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNicolas Hampton
44,638 PointsWhy don't we define the Callback object in a separate variable?
I noticed that we're defining the Callback() {} inside the call.enqueue() method. Doesn't that limit it's scope, and thus it's usefulness? Why aren't we defining it outside of the method as a member variable so we can use it again if needed, or simply for readability? Like:
Callback callback = new Callback() {
@Override
public void onFailure(Request request, IOException e) {}
@Override
public void onResponse(Response response) throws IOException {
try {
if(reposnse.isSuccessful()) {
Log.v(TAG, response.body().string());
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
}
call.enqueue(callback());
Am I missing something? Does this inherently not work if initialized outside of the enqueue method? This seems a lot clearer and pliable to me.
Ryan Deas
1,027 PointsRyan Deas
1,027 PointsGenerally, people don't write callbacks into variables as they are usually pretty specific for the case that they're being written in. Also there would be an issue with your code as you wouldn't call the
callback
variable with()
as you only put()
when you are calling a method, in this case you're calling a variable.