Created
July 29, 2023 16:34
-
-
Save fishkingsin/edbab0802a527ff21fa5c59825b41a6d to your computer and use it in GitHub Desktop.
DelayEmitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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