Skip to content

Instantly share code, notes, and snippets.

@fishkingsin
Created July 29, 2023 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fishkingsin/edbab0802a527ff21fa5c59825b41a6d to your computer and use it in GitHub Desktop.
Save fishkingsin/edbab0802a527ff21fa5c59825b41a6d to your computer and use it in GitHub Desktop.
DelayEmitter
package com.example.delayemitter
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
import java.lang.Thread.sleep
import java.util.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
private val _emitter = MutableStateFlow<Unit?>(null)
private var delayEmitter: Flow<Unit?> =
_emitter.filterNotNull().onStart {
delay(1000)
}.flowOn(Dispatchers.IO)
suspend fun start() {
_emitter.emit(Unit)
}
var job: Job? = null
fun cancel() {
job?.cancel()
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun addition_isCorrect() = runTest(UnconfinedTestDispatcher()) {
val values = mutableListOf<Unit?>()
job = launch {
delayEmitter.collect {
values.add(it)
println("${Date()} collect value $values")
}
}
job?.start()
start()
println("${Date()} value $values")
assertEquals(0, values.size)
sleep(3100)
println("${Date()} value $values")
assertEquals(1, values.size)
job?.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment