Skip to content

Instantly share code, notes, and snippets.

@houssemzaier
Last active July 17, 2022 20:48
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 houssemzaier/e2ef943626bacd97206e713ff03b0d32 to your computer and use it in GitHub Desktop.
Save houssemzaier/e2ef943626bacd97206e713ff03b0d32 to your computer and use it in GitHub Desktop.
TestSomeBehaviorSharedFlow
package com.ankorstore.account.presentation
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import org.junit.Test
class ExampleUnitTest {
@Test
fun sample1() = runTest {
launch(SupervisorJob()) {
val sut = MutableSharedFlow<Int>()
sut.onEach {
println("working , $it is emitted")
}.map {
if (it.rem(2) == 0) throw IllegalArgumentException("not odd element ! ")
it
}
.map {
it * 2
}
.onEach {
println("result $it ")
}
.retry { cause: Throwable ->
println("retry $cause ")
true
}
.launchIn(this)
delay(1_000)
(1..10).toList().map {
println("emitting $it")
sut.emit(it)
delay(2_000)
}
delay(10_000)
println("done !")
cancel()
}
}
@Test
fun sample2() = runTest {
launch(SupervisorJob()) {
val sut = MutableSharedFlow<Flow<Int>>()
sut.onEach {
println("working , $it is emitted")
} .flatMapLatest { it }
.map {
if (it.rem(2) == 0) throw IllegalArgumentException("not odd element ! ")
it
}
.map {
it * 2
}
.onEach {
println("result $it ")
}
.retry { cause: Throwable ->
println("retry $cause ")
true
}
.launchIn(this)
delay(1_000)
val data = MutableSharedFlow<Int>()
sut.emit(data)
(1..10).toList().map {
data.emit(it)
println("emitting $it")
delay(2_000)
}
delay(10_000)
println("done !")
cancel()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment