-
-
Notifications
You must be signed in to change notification settings - Fork 1
Add cold flow examples #230
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
Open
ashtanko
wants to merge
2
commits into
main
Choose a base branch
from
feature/add_coroutine_exmaples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
This file was deleted.
Oops, something went wrong.
17 changes: 17 additions & 0 deletions
17
src/main/kotlin/dev/shtanko/concurrency/coroutines/flow/cold/SearchApi.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| package dev.shtanko.concurrency.coroutines.flow.cold | ||
|
|
||
| import kotlinx.coroutines.delay | ||
|
|
||
| interface SearchApi { | ||
| suspend fun search(query: String): List<String> | ||
| } | ||
|
|
||
| // Simple implementation for testing/demo | ||
| @Suppress("MagicNumber") | ||
| class FakeSearchApi : SearchApi { | ||
| override suspend fun search(query: String): List<String> { | ||
| delay(500) // Simulate network delay | ||
| val database = listOf("Kotlin", "Coroutines", "Flow", "Ktor", "KMP", "Android") | ||
| return database.filter { it.contains(query, ignoreCase = true) } | ||
| } | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/main/kotlin/dev/shtanko/concurrency/coroutines/flow/cold/SearchManager.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package dev.shtanko.concurrency.coroutines.flow.cold | ||
|
|
||
| import kotlinx.coroutines.ExperimentalCoroutinesApi | ||
| import kotlinx.coroutines.FlowPreview | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.catch | ||
| import kotlinx.coroutines.flow.debounce | ||
| import kotlinx.coroutines.flow.distinctUntilChanged | ||
| import kotlinx.coroutines.flow.filter | ||
| import kotlinx.coroutines.flow.flatMapLatest | ||
| import kotlinx.coroutines.flow.flow | ||
|
|
||
| class SearchManager(private val api: SearchApi) { | ||
| @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) | ||
| fun getSuggestions( | ||
| queryFlow: Flow<String>, | ||
| debounceMillis: Long = 300L, // Default for production | ||
| ): Flow<List<String>> = queryFlow | ||
| .debounce(debounceMillis) | ||
| .filter { it.isNotBlank() } | ||
| .distinctUntilChanged() | ||
| .flatMapLatest { query -> | ||
| flow { emit(api.search(query)) } | ||
| } | ||
| .catch { emit(emptyList()) } | ||
| } | ||
25 changes: 25 additions & 0 deletions
25
src/main/kotlin/dev/shtanko/concurrency/coroutines/flow/cold/StockApi.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package dev.shtanko.concurrency.coroutines.flow.cold | ||
|
|
||
| import kotlinx.coroutines.delay | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.flow | ||
| import kotlinx.coroutines.flow.map | ||
|
|
||
| interface StockApi { | ||
| suspend fun fetchPrice(symbol: String): Double | ||
| } | ||
|
|
||
| fun tickerFlow(interval: Long) = flow { | ||
| while (true) { | ||
| emit(Unit) | ||
| delay(interval) | ||
| } | ||
| } | ||
|
|
||
| class StockRepository( | ||
| private val api: StockApi, | ||
| private val refreshInterval: Long = 5000L, | ||
| ) { | ||
| fun getStockPrice(symbol: String): Flow<Double> = | ||
| tickerFlow(refreshInterval).map { api.fetchPrice(symbol) } | ||
| } |
61 changes: 61 additions & 0 deletions
61
src/test/kotlin/dev/shtanko/concurrency/coroutines/flow/cold/SearchManagerTest.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| package dev.shtanko.concurrency.coroutines.flow.cold | ||
|
|
||
| import app.cash.turbine.test | ||
| import kotlinx.coroutines.ExperimentalCoroutinesApi | ||
| import kotlinx.coroutines.flow.MutableSharedFlow | ||
| import kotlinx.coroutines.test.advanceTimeBy | ||
| import kotlinx.coroutines.test.runTest | ||
| import org.junit.jupiter.api.Assertions.assertEquals | ||
| import org.junit.jupiter.api.Test | ||
|
|
||
| @OptIn(ExperimentalCoroutinesApi::class) | ||
| class SearchManagerTest { | ||
|
|
||
| private val fakeApi = FakeSearchApi() | ||
| private val manager = SearchManager(fakeApi) | ||
|
|
||
| @Test | ||
| fun `search flow should debounce and return results`() = runTest { | ||
| // Use a buffer of 1 so emissions aren't lost during setup | ||
| val queryInput = MutableSharedFlow<String>(replay = 1) | ||
| val testDebounce = 100L | ||
|
|
||
| manager.getSuggestions(queryInput, debounceMillis = testDebounce).test { | ||
| // Emit "K" | ||
| queryInput.emit("K") | ||
| advanceTimeBy(50) // Less than debounce | ||
|
|
||
| // Emit "Ko" - this should reset the timer for "K" | ||
| queryInput.emit("Ko") | ||
|
|
||
| // Advance exactly enough to trigger to debounce | ||
| advanceTimeBy(testDebounce + 1) | ||
|
|
||
| val result = awaitItem() | ||
| assertEquals(listOf("Kotlin"), result) | ||
|
|
||
| cancelAndIgnoreRemainingEvents() | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| fun `search flow should ignore duplicate consecutive queries`() = runTest { | ||
| val queryInput = MutableSharedFlow<String>(replay = 1) | ||
| val testDebounce = 100L | ||
|
|
||
| manager.getSuggestions(queryInput, debounceMillis = testDebounce).test { | ||
| // First search | ||
| queryInput.emit("Kotlin") | ||
| advanceTimeBy(testDebounce + 1) | ||
| awaitItem() | ||
|
|
||
| // Immediate duplicate search | ||
| queryInput.emit("Kotlin") | ||
| advanceTimeBy(testDebounce + 1) | ||
|
|
||
| // Assert that no new list was emitted | ||
| expectNoEvents() | ||
| cancelAndIgnoreRemainingEvents() | ||
| } | ||
| } | ||
| } |
58 changes: 58 additions & 0 deletions
58
src/test/kotlin/dev/shtanko/concurrency/coroutines/flow/cold/StockRepositoryTest.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| package dev.shtanko.concurrency.coroutines.flow.cold | ||
|
|
||
| import app.cash.turbine.test | ||
| import kotlinx.coroutines.ExperimentalCoroutinesApi | ||
| import kotlinx.coroutines.flow.take | ||
| import kotlinx.coroutines.flow.toList | ||
| import kotlinx.coroutines.test.advanceTimeBy | ||
| import kotlinx.coroutines.test.runTest | ||
| import org.junit.jupiter.api.Assertions.assertEquals | ||
| import org.junit.jupiter.api.Test | ||
| import org.mockito.kotlin.mock | ||
| import org.mockito.kotlin.whenever | ||
|
|
||
| @OptIn(ExperimentalCoroutinesApi::class) | ||
| class StockRepositoryTest { | ||
|
|
||
| private val mockApi = mock<StockApi>() | ||
|
|
||
| @Test | ||
| fun `test will not hang because turbine cancels the scope`() = runTest { | ||
| // We set a small interval | ||
| val repository = StockRepository(mockApi, refreshInterval = 100L) | ||
| val symbol = "AAPL" | ||
|
|
||
| whenever(mockApi.fetchPrice(symbol)).thenReturn(150.0, 151.0) | ||
|
|
||
| // The 'test' extension starts the 'while(true)' loop | ||
| repository.getStockPrice(symbol).test { | ||
|
|
||
| assertEquals(150.0, awaitItem()) | ||
|
|
||
| advanceTimeBy(100L) | ||
|
|
||
| assertEquals(151.0, awaitItem()) | ||
|
|
||
| // This is the "Kill Switch" | ||
| // It throws a CancellationException inside the Repository's loop | ||
| cancelAndIgnoreRemainingEvents() | ||
| } | ||
|
|
||
| // If we reach here, the loop is confirmed DEAD. | ||
| } | ||
|
|
||
| @Test | ||
| fun `alternative using take to force a finite flow`() = runTest { | ||
| val repository = StockRepository(mockApi, refreshInterval = 0L) | ||
| whenever(mockApi.fetchPrice("AAPL")).thenReturn(100.0, 101.0, 102.0) | ||
|
|
||
| // 'take(3)' turns the endless flow into a finite one that | ||
| // automatically closes after 3 emissions. | ||
| val results = repository.getStockPrice("AAPL") | ||
| .take(3) | ||
| .toList() // Collects everything into a list | ||
|
|
||
| assertEquals(3, results.size) | ||
| assertEquals(102.0, results.last()) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.