Trying To Get Retrofit Onresponse Executed First
Solution 1:
To get the result from the background thread to the main thread I had to use AsyncTask.get(). By using that I could see a value in my stores
variable instead of having a null value.
Below you can see my code for those who want to see it:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)public Response<List<Store>> getSubprises()throws IOException, ExecutionException, InterruptedException {
LongOperationlongOperation=newLongOperation();
longOperation.execute("");
stores = longOperation.get();
return stores;
}
privateclassLongOperationextendsAsyncTask<String, Void, Response<List<Store>>> {
@Overrideprotected Response<List<Store>> doInBackground(String... params) {
//System.out.println("doInBackground executed second");try {
Call<List<Store>> call = subpriseAPI.listStores();
stores=call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return stores;
}
@OverrideprotectedvoidonPreExecute() {
//Can't put the call here because this is the main thread//System.out.println("onPreExecute first");
}
@OverrideprotectedvoidonPostExecute(Response<List<Store>> result) {
//Can't put the call here because this is the main thread
}
}
Solution 2:
i think you'd be better off letting Retrofit invoke the calls internally on its internal HTTP executor. this would involve changing your API interface to something like this:
publicinterfaceSubpriseAPI {
@GET("api/locations/get")
List<Store> listStores();
}
... and including any relevant configuration for Retrofit to handle the deserialization into your Store
type.
however, if you want to invoke the calls yourself, you might consider hosting your own executor instance (or however you want to run your worker threads), something like this (not this exact implementation, but you should get the idea):
classStoreService {
...privatefinalExecutorService executorService =Executors.newCachedThreadPool();
...publicResponse<List<Store>> getSubprises() {
executorService.submit(new Callable<List<Store>>() {
@OverridepublicList<Store> call() throwsException {
finalCall<List<Store>> call = subpriseAPI.listStores();
try {
if(stores == null) {
stores = new ArrayList<>();
} else {
stores.clear();
}
stores.addAll(call.execute());
System.out.println("stores "+ stores);
} catch (IOException e) {
e.printStackTrace();
}
}
}).get();
...
UPDATE
i didn't realize you were (apparently) using Retrofit 2. i've had a chance to experiment a bit and this is what i came up with.
here are the relevant dependencies i have in my app/build.gradle:
compile'com.squareup.retrofit:retrofit:2.0.0-beta2'compile'com.squareup.retrofit:converter-gson:2.0.0-beta2'
...here is my API interface:
publicinterfaceApi {
@Headers("Accept: application/json")
@GET("/v2/567595ad0f0000ea23315d02")
public Call<List<Widget>> widgets();
}
...here is a simple DTO i'll be unmarshalling some JSON into:
publicclassWidget{
publicString value;
}
...and finally, here is my test activity: public class Retrofit2TestActivity extends AppCompatActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Api mockyApi = newRetrofit.Builder()
.baseUrl("http://www.mocky.io")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(Api.class);
mockyApi.widgets().enqueue(newCallback<List<Widget>>() {
@OverridepublicvoidonResponse(Response<List<Widget>> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.d(Retrofit2TestActivity.class.getName(), "## widgets.size() == " + response.body().size());
} else {
Log.d(Retrofit2TestActivity.class.getName(), String.format("## response was NOT successful [%d]", response.code()));
}
}
@OverridepublicvoidonFailure(Throwable t) {
Log.d(Retrofit2TestActivity.class.getName(), String.format("## response was NOT successful [%s]", t.getMessage()));
}
});
}
}
obviously you should substitute my Widget
for your Store
type. beyond that, manipulating the List<Store>
as a normal member variable of your activity should be straightforward.
i hope that helped.
Post a Comment for "Trying To Get Retrofit Onresponse Executed First"