I am facing a dilemma here. Earlier I used to use Core Java Library HttpUrlConnection to get JSON data over the web and use to parse it with GSON. Earlier these days my university teacher told me to use Retrofit library instead. Thinking of it a better and optimized way to code, I started working with it.
I loved its simplicity and rich feature but here I am struggling a lot due to of Callback anonymous inner class. Due to of it I am unable to pass the objects to other methods of mail application files, which I used to handle easily when I worked with HttpUrlConnection. Now here is my question, am I going any wrong, or is it really not a wise decision to use Retrofit with my java applications and I should stick to HttpUrlConnection.
Please let me know!
I am pasting a code below just to explain my point here:
I can't say whether it's wise to use this library - I know little about it, and it's unclear why your instructor recommended it.
What I can say is that for one project I've recently switched from Java's built-in HTTP library to https://square.github.io/okhttp/, which has a much nicer API, IMO. It's so nice to work with that it's going to be my default HTTP client library going forward, though.
Or does that "enqueue" method actually cause something to run asynchronously and call the callback method at an unpredictable future time? I'm not familiar with Retrofit either but I wouldn't expect asynchronous behaviour there.
I'm pretty sure you're right. (Lame excuse: it's hard for me to write some code which I can play with because there's too many other things to set up.)
My next idea was that the class that the getProductById method is part of could have a setProduct(Product) method which would be called in the anonymous class. Maybe that might work -- but your feeling that you would have to change your programming a lot, I'm pretty sure that's right as well.
You could consider using some kind of a data structure (Queue?) inside the method getProductId method but outside the inner class, and add the data you get from the callback to it, then use some polling (or similar) to send the data from the method.
This is just an example way of doing that, but need to be analysed and properly designed depending on your application flow/model.