1

I may have stumbled upon a bug in Jetpack Compose when using Scaffold and Kotlin Flow. Before submitting a Bugreport, I'd like to know if I made some error.

There is a minimal runnable example under this link. This is a minimal android app showing the problem, it contains the same code as pasted below (wrapped in an Activity). I run the project on an Android simulator running API 33.

Below is the code that triggers the issue. After pressing the button, the two "Text" Composables in the ContentScreen and TopBar Composable diverge, even though they should represent the same value.

This code is reduced to the minimum needed to reproduce the problem. Originally all of this is more complex and simple workarounds like inlining the "TopBar" functions are difficult.

@Composable
fun MainScreen() {
    var id by remember { mutableStateOf(0) }
    val contentModel = ContentModel(id)

    ContentScreen(contentModel, nextModel = {
        id = Random.nextInt(1000)
    })
}

@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun ContentScreen(contentModel: ContentModel, nextModel: () -> Unit) {
    Scaffold(topBar = { TopBar(contentModel) }) {
        Column {
            Text("This number should match ${contentModel.id}")
            Button(onClick = nextModel) { Text("Generate new number") }
        }
    }

    // accessing flow is necessary for the bug to appear
    contentModel.contentFlow.collectAsState(0).value.toString()
}

@Composable
private fun TopBar(contentModel: ContentModel) = Text("This number should match ${contentModel.id}")

data class ContentModel(val id: Int)  {
    /** This flow represents data fetched in the background based on the value of id. */
    val contentFlow: Flow<Int>
        get() = flow {
            this.emit(id)
        }
}
findusl
  • 2,454
  • 8
  • 32
  • 51

0 Answers0