-
Notifications
You must be signed in to change notification settings - Fork 1.9k
combine(flow1, flow2) does not work instantly #2280
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
Comments
It is expected behavior. Coroutines are asynchronous. The "immediate" dispatcher is a bit of performance-optimization trick, not a guarantee of any kind of synchrony in execution and it still, in fact, uses an event queue under the hood, that can get coroutines execution deferred. If you are looking to get "instantly computed" properties, you should use some other framework or create your own framework. Flow is inherently designed to be asynchronous, as opposed to being synchronous. |
Is the same true for |
This looks somewhat similar to #2082. |
You cannot expect synchronous execution with |
@elizarov @Test
fun `state flow is collected instantly`() = runBlockingTest {
val flow = MutableStateFlow("")
var result = ""
val job = launch {
flow.collect {
result += it
}
}
result += "1"
flow.value = "A"
result += "2"
flow.value = "B"
result += "3"
flow.value = "C"
assertEquals("1A2B3C", result)
job.cancel()
} |
There is no such guarantee. In simple cases it will, indeed, work seemingly synchronously. In complex nested cases, when you mutate a value inside another mutation (which has been already immedaitely-dispatched) it will not work this way. |
@elizarov |
There is a guarantee that it updates as soon as possible. Whenever possible updates are synchronous. But this happens not because it is designed to provide synchronous updates, it happens because it is designed to provide updates as fast as possible which is not the same as you'd find in synchronous data-binding frameworks. As long as you use it for a direct viewmodel -> view communication, though, it will happen fast and synchronously. |
Thanks 👍 |
Hi.
I am writing a mini-framework with reactive properties. One of the core concepts in this framework is a computed property. This property recalculates its value automatically whenever values of some other properties are changed.
For example:
My framework uses
MutableStateFlow
andcombine
under the hood.The problem is that it is not always works as expected. The computed value is not updated instantly in some cases.
For example:
I wrote a test to reproduce the problem:
In the real code I use
Main.immediate
dispatcher. That's why I expect an instant recalculation.Take a look, please.
If it is an expected behavior, how can I solve my problem?
The text was updated successfully, but these errors were encountered: