Commit 8bfdc54a by pye52

修复在非主线程add和remove observer导致崩溃的问题

parent 9dfccb66
......@@ -77,6 +77,24 @@ public class PayOfflineViewModel extends ViewModel {
SCTaskExecutor.getInstance().schedule(runnable, REQUEST_DELAY, TimeUnit.MILLISECONDS);
}
private void addDataObserver() {
if (SCTaskExecutor.getInstance().isMainThread()) {
payOfflineData.observeForever(dataObserver);
} else {
SCTaskExecutor.getMainThreadExecutor()
.execute(() -> payOfflineData.observeForever(dataObserver));
}
}
private void removeDataObserver() {
if (SCTaskExecutor.getInstance().isMainThread()) {
payOfflineData.removeObserver(dataObserver);
} else {
SCTaskExecutor.getMainThreadExecutor()
.execute(() -> payOfflineData.removeObserver(dataObserver));
}
}
private void cancelTimeout() {
if (timeoutFuture == null) return;
timeoutFuture.cancel(true);
......@@ -97,7 +115,7 @@ public class PayOfflineViewModel extends ViewModel {
@Override
public void onOpen(ServerHandshake data) {
payOfflineData.observeForever(dataObserver);
addDataObserver();
// 只要Socket链接成功,则搜索数据库需要离线支付的订单,并发送给后台
cancelTimeout();
TimeoutRunnable timeoutRunnable = new TimeoutRunnable();
......@@ -124,12 +142,12 @@ public class PayOfflineViewModel extends ViewModel {
@Override
public void onClose(int code, String reason, boolean remote) {
payOfflineData.removeObserver(dataObserver);
removeDataObserver();
}
@Override
public void onError(Exception ex) {
payOfflineData.removeObserver(dataObserver);
removeDataObserver();
}
};
......@@ -182,7 +200,7 @@ public class PayOfflineViewModel extends ViewModel {
cancelTimeout();
payRequest = null;
// 所有离线订单处理完毕后,断开数据监听
payOfflineData.removeObserver(dataObserver);
removeDataObserver();
LogUtils.d(TAG, "所有离线订单处理完毕");
return;
}
......@@ -228,7 +246,7 @@ public class PayOfflineViewModel extends ViewModel {
}
payDataRepository.updatePayData(dataList);
if (ids.length() > 0) {
LogUtils.d(TAG, "上传的所有离线支付订单号: " + ids.substring(0, ids.length() - 1));
LogUtils.d(TAG, "上传的所有离线支付订单号: " + ids.substring(0, ids.length() - 1));
}
payRequest = null;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment