How can I make Jetpack Compose AndroidView run a new viewBlock instance on new parameters?

2.5k views Asked by At

I have a Jetpack Composable function that wraps a WebView instance in an AndroidView:

@Composable
fun createWebView(url: String, viewCache: WebViewCache) {

    AndroidView(viewBlock = { context ->
        viewCache.get(url, context)
    }, update = { wv ->
        Log.d("we are just updating")
    }, modifier = Modifier.fillMaxSize())
}

It works for the first url passed in, but for subsequent different urls, only the update method is called. Is it possible to make the viewBlock lambda be invoked given different parameters? I realize I could call loadUrl on the same WebView instance, but would prefer to cache each url's WebView for my app.

1

There are 1 answers

0
2jan222 On BEST ANSWER

You want to change the state of the Composable, thus you need a mutableState for your URL (mutableStateOf(initUrl)) which is the key to get the cached WebView. I am not familiar with WebView but I would guess you get the new URL inside the update Lambda. Nether the less from wherever you get the new URL you have to update the URL state to tell Compose Runtime to update your UI.

@Composable
fun createWebView(initUrl: String, viewCache: WebViewCache) {
    val context = ContextAmbient.current
    val urlState = remember(initUrl) { mutableStateOf(initUrl) }
    val cacheView = remember(urlState.value, context) {
        viewCache.get(urlState.value, context)
    }
    AndroidView(
        viewBlock = { cacheView },
        update = { wv -> urlState.value = "newvalue" },
        modifier = Modifier.fillMaxSize())
}