我的問題是在我的應用程式中不顯示通知。
我的應用程式每次按下按鈕時都會這樣做,我會創建新執行緒并顯示通知,其中包含執行緒正在運行或等待的資訊(這作業正常)。然后,如果執行緒正在運行,它會隨機休眠 5-10 秒并從 rest api 獲取資料,并且應該顯示執行緒完成的通知(不顯示此通知)。
再次按下按鈕后會顯示精細通知。正如您在影像中看到的那樣。
圖片:

建構式視圖:
public MainView() {
Button ipButton = getIpButton();
setMargin(true);
setHorizontalComponentAlignment(Alignment.START, ipButton);
add(ipButton);
}
按鈕:
private Button getIpButton() {
final UI ui = UI.getCurrent();
final VaadinSession session = VaadinSession.getCurrent();
Button ipButton = new Button("My IP");
AtomicInteger orderIndex = new AtomicInteger();
ipButton.addClickListener(_e -> {
int orderThread = orderIndex.getAndIncrement();
openBeginNotification(orderThread);
executor.submit(() -> {
try {
UI.setCurrent(ui);
VaadinSession.setCurrent(session);
long sleepTime = (long) (Math.random() * (10 - 5) 5);
System.out.printf("%d: %ds\n", orderThread, sleepTime);
Thread.sleep(sleepTime * 1000);
IpDTO ip = restTemplate.getForObject("http://ip.jsontest.com/", IpDTO.class);
System.out.printf("%d: %s\n", orderThread, ip);
try {
VaadinSession.getCurrent().lock();
getFinishNotification(orderThread).open(); // here not show notification
VaadinSession.getCurrent().unlock();
} catch (Exception e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
});
return ipButton;
}
通知方式:
private void openBeginNotification(int orderThread) {
Notification notification;
if (executor.getActiveCount() == MAX_THREADS) {
// thread is in front
notification = getWaitNotification(orderThread);
} else {
// thread run
notification = getRunNotification(orderThread);
}
notification.open();
}
private Notification getRunNotification(int orderThread) {
return getNotification("Task " orderThread ": run", NotificationVariant.LUMO_PRIMARY);
}
private Notification getWaitNotification(int orderThread) {
return getNotification("Task " orderThread ": wait", NotificationVariant.LUMO_CONTRAST);
}
private Notification getFinishNotification(int orderThread) {
return getNotification("Task " orderThread ": finish", NotificationVariant.LUMO_SUCCESS);
}
private Notification getNotification(String notificationText, NotificationVariant variant) {
Notification notification = new Notification(notificationText, 1000);
notification.addThemeVariants(variant);
return notification;
}
uj5u.com熱心網友回復:
首先,您需要啟用@Push讓 Vaadin 打開一個 websocket 連接,使服務器可以直接向瀏覽器發送訊息,而無需等待瀏覽器發送請求更改的訊息(當您單擊按鈕時會發生這種情況)。根據@Push您使用的 Vaadin 版本,注釋應該位于不同的位置,因此請參閱檔案以找到正確的位置。
其次,請使用UI::access而不是手動執行setCurrent和鎖定。雖然我在您的示例中沒有發現任何會破壞快樂案例的內容,但您仍然需要考慮一大堆邊緣案例。例如,您沒有進行清理,setCurrent這可能會導致記憶體泄漏,并且您沒有解鎖以防與通知相關的某些內容引發例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486650.html
上一篇:如何正確使用執行緒
