Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update withLatestFrom.kt #224

Merged
merged 5 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
),
)
}
}
Loading