8

Checking out this example with list to scroll using state and Coroutines as

@Composable
fun ScrollingList() {
    val listSize = 100
    // We save the scrolling position with this state
    val scrollState = rememberLazyListState()
    // We save the coroutine scope where our animated scroll will be executed
    val coroutineScope = rememberCoroutineScope()

    Column {
        Row {
            Button(onClick = {
                coroutineScope.launch {
                    // 0 is the first item index
                    scrollState.animateScrollToItem(0)
                }
            }) {
                Text("Scroll to the top")
            }

            Button(onClick = {
                coroutineScope.launch {
                    // listSize - 1 is the last index of the list
                    scrollState.animateScrollToItem(listSize - 1)
                }
            }) {
                Text("Scroll to the end")
            }
        }

        LazyColumn(state = scrollState) {
            items(listSize) {
                ImageListItem(it)
            }
        }
    }
}

Which works fine for suspending function

suspend fun animateScrollToItem(
    /*@IntRange(from = 0)*/
    index: Int,
    /*@IntRange(from = 0)*/
    scrollOffset: Int = 0
) {
    doSmoothScrollToItem(index, scrollOffset)
}

If i change coroutine scope to

val coroutineScope = CoroutineScope(Dispatchers.Main)

It returns

java.lang.IllegalStateException: A MonotonicFrameClock is not available in this CoroutineContext. Callers should supply an appropriate MonotonicFrameClock using withContext.

What does this mean, and is rememberCoroutineScope() only way to provide coroutineScope to this function?

Thracian
  • 43,021
  • 16
  • 133
  • 222

1 Answers1

12

As animateScrollToItem is composable function it needs to be called within the scope of Composition.

As documentation states

rememberCoroutineScope is a composable function that returns a CoroutineScope bound to the point of the Composition where it's called. The scope will be cancelled when the call leaves the Composition.