我正在尝试使用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);
尝试通过以下方式获取工作信息的 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);
}
}
});
但观察者并没有被击中。有什么想法吗?