我正在尝试使用RxWorker访问工作者类的工作信息。下面是工人阶级
public class OrderSyncWorker extends RxWorker {
@NonNull
@Override
public Single<Result> createWork() {
List<Order> ordersToBeSynced = databaseRepository.getNonSyncedOrders();
JSONArray orders = new JSONArray();
try {
JSONObject request = new JSONObject(); mApiManager.syncOrders(request).flatMap((Function<ApiResponse, Single<Result>>) apiResponse -> {
if (apiResponse.getSuccess() == 1) {
databaseRepository.syncAllOrders();
mNotificationUtils.showNotification("Orders synced", "", true);
return Single.just(Result.success());
} else {
mNotificationUtils.showNotification("Orders not synced", "Unknown error", true);
return Single.just(Result.failure());
}
}).onErrorReturn(throwable -> {
mNotificationUtils.showNotification("Orders not synced", Utils.parseError(throwable), true);
return Result.failure();
});
subscription.subscribe();
return subscription;
} catch (JSONException e) {
return Single.just(Result.failure());
}
}
}
这是我初始化工作请求的方式。
Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED)
.build();
OneTimeWorkRequest orderSyncRequest = new OneTimeWorkRequest.Builder(OrderSyncWorker.class)
.setInputData(new Data.Builder().putString("macId", macId).build())
.setConstraints(constraints)
.addTag("sync_orders")
.build();
WorkManager.getInstance().enqueue(orderSyncRequest);
试图像这样获得workinfo livedata
workInfos = WorkManager.getInstance().getWorkInfosByTagLiveData("sync_orders");
viewModel.observeonWorkStatus().observe(this, new Observer<List<WorkInfo>>() {
@Override
public void onChanged(@Nullable List<WorkInfo> workInfos) {
if (workInfos == null || workInfos.isEmpty()) {
return;
}
WorkInfo workInfo = workInfos.get(0);
boolean finished = workInfo.getState().isFinished();
if (!finished) {
syncButton.setEnabled(false);
} else {
syncButton.setVisibility(View.GONE);
}
}
});
但是观察者并没有受到打击。有什么想法吗?
答案 0 :(得分:0)
首先,关于不为标签使用字符串文字的个人说明,请考虑为其定义常量:
static final String TAG_SYNC_ORDERS = "SYNC_ORDERS";
查看您的代码,看来您是从WorkRequest获取LiveData的:
LiveData<List<WorkInfo>> workInfos = WorkManager.getInstance().getWorkInfosByTagLiveData("sync_orders");
但随后您使用ViewModel中的另一个LiveData(?):
viewModel.observeonWorkStatus()
我认为这些是相同的。如果没有,那是个问题。
现在重写您的LiveData观察者:
static final String TAG_SYNC_ORDERS = "SYNC_ORDERS";
LiveData<List<WorkInfo>> workInfos = WorkManager.getInstance().getWorkInfosByTagLiveData(TAG_SYNC_ORDERS);
workInfos.observe(this, listOfWorkInfo -> {
// If there are no matching work info, do nothing
if (listOfWorkInfo == null || listOfWorkInfo.isEmpty()) {
return;
}
// We only care about the one output status.
WorkInfo workInfo = listOfWorkInfo.get(0);
boolean finished = workInfo.getState().isFinished();
if (!finished) {
syncButton.setEnabled(false);
} else {
syncButton.setVisibility(View.GONE);
}
});
您可以参考WorkManager codelab以获得更多类似的示例。