Skip to content

Commit

Permalink
Minor cleanup in HotStateProducer
Browse files Browse the repository at this point in the history
  • Loading branch information
sellmair committed Jul 17, 2024
1 parent 37030ab commit 18653c2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,15 @@ public fun <T : State?> CoroutineScope.launchStateProducer(
produce: suspend StateProducerScope<T>.() -> Unit
): Job {
val newCoroutineContext = (this.coroutineContext + coroutineContext).let { base -> base + Job(base.job) }
val producerJob = newCoroutineContext.job
val states = newCoroutineContext.statesOrThrow
val coroutineScope = CoroutineScope(newCoroutineContext)

val hotFlow = stateProducerFlow(produce).shareIn(coroutineScope, started, replay = 1)

coroutineScope.launch {
currentCoroutineContext().statesOrThrow.setState(key, hotFlow)
states.setState(key, hotFlow)
}

return coroutineScope.coroutineContext.job
return producerJob
}



22 changes: 6 additions & 16 deletions evas/src/commonTest/kotlin/StatesTest.kt
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
@file:OptIn(ExperimentalCoroutinesApi::class)

package io.sellmair.evas

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.isActive
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.currentTime
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.*
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds

Expand Down Expand Up @@ -120,7 +110,7 @@ class StatesTest {
@Test
fun `test - keepActive`() = runTest(States()) {
launchStateProducer(keepActive = 3.seconds + 1.milliseconds) { _: ColdState.Key ->
while(currentCoroutineContext().isActive) {
while (currentCoroutineContext().isActive) {
ColdState(currentTime).emit()
delay(1.seconds)
}
Expand Down Expand Up @@ -156,7 +146,7 @@ class StatesTest {
launchStateProducer(keepActive = 2.seconds + 1.milliseconds) { _: ColdState.Key ->
assertFalse(launched, "Another producer was already launched!")
launched = true
while(currentCoroutineContext().isActive) {
while (currentCoroutineContext().isActive) {
ColdState(currentTime).emit()
delay(1.seconds)
}
Expand Down

0 comments on commit 18653c2

Please sign in to comment.