-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
sample() operator on Hot Flow makes runTest hang #4068
Comments
Both of these tests are written incorrectly, because they break structured concurrency. Manually creating a A correct test would be something like this: @Test
fun noRepro() = runTest {
val flow = MutableSharedFlow<Int>()
backgroundScope.launch {
flow.collect {}
}
} |
Thank you for your reply @dkhalanskyjb. But if both tests are written incorrectly, shouldn't both of them hang? My concern is that there are probably plenty of Android Here is a more realistic example that hopefully conveys what I am getting at: class ReproViewModel : ViewModel() {
private val flow = MutableSharedFlow<Int>()
init {
viewModelScope.launch {
flow
.sample(300L) // Test on longer hangs if you comment out this line
.collect {}
}
}
}
class ReproTest {
// Normally this @Before/@After would be extracted out into a reusable JUnit rule.
@Before
fun setUp() {
Dispatchers.setMain(StandardTestDispatcher())
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun repro() = runTest {
ReproViewModel()
}
} |
Yes, that's better, thanks. For testing coroutines on Android, the recommended approach is to inject the scope: https://developer.android.com/kotlin/coroutines/test#inject-scope This way, you can use In the "setting the Main dispatcher" section, one-shot operations are shown, ones that perform some task and then finish. For testing such tasks, just setting the main dispatcher is fine. When a task in a The reason |
Describe the bug
Using
runTest
while testing an Android ViewModel that usesviewModelScope
to launch a coroutine that collects from aMutableSharedFlow
that gets thesample()
operator applied to it, the test hangs forever. If I remove thesample()
operator, the test completes.Provide a Reproducer
The text was updated successfully, but these errors were encountered: