我正在使用Work Manager进行网络调用并获取一些数据,为此我使用了OneTimeRequest。调用在worker类中完美响应,但在观察工作的生命周期所有者中返回空结果。
workManager= WorkManager.getInstance();
OneTimeWorkRequest.Builder encryptionWork =new OneTimeWorkRequest.Builder(NetworkWorker.class);
getUsersWorkReq=encryptionWork.setInputData(getWorkerInput(EXPERT_LIST_REQUEST))
.addTag(Constant.WORK_GETUSER)
.build();
workManager.enqueue(getUsersWorkReq);
观察工作类的响应
workManager.getStatusById(getUsersWorkReq.getId()).observe(this, workStatus -> {
if (workStatus != null && workStatus.getState().isFinished()) {
String status=workStatus.getOutputData().getString(Constant.WORK_RESULT);
String response=workStatus.getOutputData().getString(Constant.WORK_RESPONSE);
if(status!=null && !status.equalsIgnoreCase("")){
}
}
});
但问题在于,响应字符串始终为空!! 即使工作管理器已完成任务并且网络响应存在于工作器中,但当我使用 setOutputData 时,它会给出空数据。
outPut = new Data.Builder()
.putString(Constant.WORK_RESULT,Constant.WORK_SUCCESS)
.putString(Constant.WORK_RESPONSE, String.valueOf(response.body()))
.build();
Log.e("WORKER", "onResponse: "+ response.body().getMsg() );
setOutputData(outPut);
工作者类
public class NetworkWorker extends Worker {
Data outPut;
@NonNull
@Override
public Result doWork() {
ApiService service = RetrofitInstance.getRetrofitInstance().create(ApiService.class);
Call<ExpertListResponse> call = service.get_recommended_users();
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<ExpertListResponse>() {
@Override
public void onResponse(Call<ExpertListResponse> call, Response<ExpertListResponse> response) {
//onFinishedListener.onFinished(requestTag, response.body() != null ? response.body().getExpertInfo() : null);
Data outPut = new Data.Builder()
.putString(Constant.WORK_RESULT,Constant.WORK_SUCCESS)
.putString(Constant.WORK_RESPONSE, String.valueOf(response.code()))
.build();
Log.e("WORKER", "onResponse: "+ response.body().getMsg() );
setOutputData(outPut);
}
@Override
public void onFailure(Call<ExpertListResponse> call, Throwable t) {
//onFinishedListener.onFailure(requestTag,t);
Data outPut = new Data.Builder()
.putString(Constant.WORK_RESULT,Constant.WORK_FAILURE)
.putString(Constant.WORK_RESPONSE, String.valueOf(t))
.build();
setOutputData(outPut);
}
});
return Result.SUCCESS;
}
}
doWork()
在onResponse()
触发之前就返回了,因此输出还没有被设置。 - greenapps