Setting image src continuously, blocks the UI

I have a Vaadin 19 application which loads an image from the backend API which returns it as a StreamResource.
A thread refreshes this image continuously (multiple times per second).

Problems:

  • when this is done before the image is actually shown in the UI the first time, the UI seems to block
  • how can I check that the image is fully loaded from Java before starting the timer?
private final Image image;

public Main() {
	image = new Image();
	add(image);
}

@Override
protected void onAttach(AttachEvent attachEvent) {
	Timer timer = new Timer("ImageUpdateTimer");
	timer.schedule(new UpdateImageTask(attachEvent.getUI()), 0, 150);
}

private void updateImage() {
	StreamResource imageSrc = service.getImage();
	if (imageSrc != null) {
		image.setSrc(imageSrc);
	}
}

private class UpdateImageTask extends TimerTask {
	private final UI ui;
	UpdateImageTask(UI ui) {
		this.ui = ui;
	}
	@Override
	public void run() {
		ui.access(Main.this::updateImage);
	}
}

Hi,

This sounds like a case you should not do on the Java side. If you do it on the client side instead you can do the logic like:

  1. Load an image
  2. When the image is loaded: wait for N ms and then load a new image

With your server driven approach you have the problems:

  1. You have no idea when the client is finished loading the first image, unless you add a listener and pass that information to the server separately
  2. You have no idea how long it takes for the client to load the image. If it takes 200ms to update the image and you push an update every 150ms, you have effectively frozen the UI forever.
  3. Even if a “normal” update it quicker than the defined delay, unexpected things happen. Once the client machine lags a bit, you might freeze everything

Thanks for the feedback Artur!