Skip to content

Commit

Permalink
fix(withLatestFrom): fix the bug that the other Flow is not cancelled…
Browse files Browse the repository at this point in the history
… after the main Flow is completed (#224)

* Update withLatestFrom.kt

* import

* - `withLatestFrom`: fix the bug that the other Flow is not cancelled after the main Flow is completed.

* - `withLatestFrom`: fix the bug that the other Flow is not cancelled after the main Flow is completed.
  • Loading branch information
hoc081098 authored Jan 29, 2024
1 parent a01bbac commit 7f7f791
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Change Log

## [Unreleased] - TBD

### Fixed

- `withLatestFrom`: fix the bug that the other Flow is not cancelled after the main Flow is completed.

## [0.7.5] - Jan 28, 2024

### Changed
Expand Down
6 changes: 4 additions & 2 deletions src/commonMain/kotlin/com/hoc081098/flowext/withLatestFrom.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ package com.hoc081098.flowext
import com.hoc081098.flowext.internal.AtomicRef
import com.hoc081098.flowext.internal.INTERNAL_NULL_VALUE
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
Expand All @@ -48,7 +49,7 @@ public fun <A, B, R> Flow<A>.withLatestFrom(

try {
coroutineScope {
launch(start = CoroutineStart.UNDISPATCHED) {
val otherCollectionJob = launch(start = CoroutineStart.UNDISPATCHED) {
other.collect { otherRef.value = it ?: INTERNAL_NULL_VALUE }
}

Expand All @@ -60,6 +61,7 @@ public fun <A, B, R> Flow<A>.withLatestFrom(
),
)
}
otherCollectionJob.cancelAndJoin()
}
} finally {
otherRef.value = null
Expand All @@ -69,4 +71,4 @@ public fun <A, B, R> Flow<A>.withLatestFrom(

@Suppress("NOTHING_TO_INLINE")
public inline fun <A, B> Flow<A>.withLatestFrom(other: Flow<B>): Flow<Pair<A, B>> =
withLatestFrom(other) { a, b -> a to b }
withLatestFrom(other, ::Pair)
12 changes: 12 additions & 0 deletions src/commonTest/kotlin/com/hoc081098/flowext/WithLatestFromTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,16 @@ class WithLatestFromTest : BaseTest() {
),
)
}

@Test
fun cancelOtherFlowAfterSourceFlowCompleted() = runTest {
flowOf(1)
.withLatestFrom(neverFlow().startWith(2))
.test(
listOf(
Event.Value(1 to 2),
Event.Complete,
),
)
}
}

0 comments on commit 7f7f791

Please sign in to comment.