Programatically control page title of a View

Jmix 2.2.3

I need to change a View page title during runtime.
The end result should be like this Change title of the view at runtime
But this doesn’t work for me because it happens too early, I need to do it after the data components are initialized, so that I can construct the page title from the data.

Kind regards,
Mladen

    @Subscribe
    private fun onReady(event: ReadyEvent) {
        editedEntity.name?.let(::setPageTitle)
    }

    fun setPageTitle(title: String) {
        when (val window = getParentWindow(this)) {
            is StandardMainView -> {
                findComponent(window, "viewTitle").getOrNull()
                    ?.let { it as? HasText }
                    ?.let { it.text = title }
            }
            is Dialog -> {
                window.headerTitle = title
            }
        }
    }

    fun getParentWindow(component: Component): Component? {
        return when (val parent = component.parent.getOrNull()) {
            is StandardMainView -> parent
            is Dialog -> parent
            else -> parent?.let { getParentWindow(it) }
        }
    }

Thank you Yaroslav, this is very nice Kotlin help.
I was able to use this to do it with Java.
I found out that to change the page title, as in the title on the browser tab (Chrome) one can do this:
getUI().ifPresent(ui -> ui.getPage().setTitle(pageTitle));
and to change the View title
getUI().ifPresent(ui -> ui.getPage().executeJs("document.getElementById('viewTitle').textContent = $0", pageTitle));
From your example we can also learn that it is not the same if the View is a dialog or not, so we need to test that if we are to change it in general.

Kind regards,
Mladen