Skip to content

Undispatched collectLatest #3681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dovchinnikov opened this issue Mar 14, 2023 · 2 comments
Open

Undispatched collectLatest #3681

dovchinnikov opened this issue Mar 14, 2023 · 2 comments

Comments

@dovchinnikov
Copy link
Contributor

dovchinnikov commented Mar 14, 2023

Use case

This a contrived example.

class MyCheckBox(cs: CoroutineScope, initialValue: Boolean): JCheckBox() {
  private val vm = MutableStateFlow(initialValue) // view model
  init {
    [email protected] = initialValue
    cs.launch {
      vm.collectLatest {
        [email protected] = it
      }
    }
  }
}

Instead of duplicating the logic, I'd like to write a single lambda, which would react on VM changes. The applying of VM state to the UI could take a while, and can suspend. We have a case, where some loading indication happens, then the final state is shown, but if the state is changed during loading, it should be kept on screen to avoid flickering.

It's currently possible to collect in an undispatched coroutine, if the value is available, then it's applied immediately during construction of the UI component.

cs.launch(start = CoroutineStart.UNDISPATCHED) {
  vm.collect {
    [email protected] = it
  }
}

But with collectLatest, the block is always dispatched to be executed later.

API-shape

I think this issue should be considered together with #3679 and #3533.
Since collectLatest launches new coroutines, it should accept start and context parameters somehow, and it should accept CoroutineScope lambda to be consistent with launch/async

@dovchinnikov
Copy link
Contributor Author

dovchinnikov commented Feb 15, 2024

I think UNDISPATCHED should be used to fix #1825 instead ATOMIC start (which forces dispatch).

15112a6

This way, an additional parameter is not needed in the API, and collectLatest will behave like collect w.r.t. to dispatch logic.

@dovchinnikov
Copy link
Contributor Author

kotlinx.coroutines.flow.internal.ChannelFlowTransformLatest#flowCollect hints that dispatch is not needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant