kotlin-flow
Kotlin Flow - StateFlow, SharedFlow, operators, testing
When & Why to Use This Skill
This Claude skill provides comprehensive guidance and code implementations for Kotlin Flow, covering StateFlow, SharedFlow, and complex reactive operators. It helps developers build robust, asynchronous data streams and implement efficient state management in Kotlin-based applications, specifically optimized for Android development and reactive programming patterns.
Use Cases
- State Management: Implementing StateFlow in ViewModels to handle UI state reactively and ensure data consistency across configuration changes.
- Search Optimization: Utilizing Flow operators like debounce, filter, and distinctUntilChanged to build high-performance search-as-you-type functionality that minimizes redundant API calls.
- Data Stream Orchestration: Combining multiple asynchronous data sources (e.g., network responses and local database updates) into a unified stream using the combine operator.
- Reliable Testing: Writing robust unit tests for asynchronous streams using the Turbine library to validate emission sequences and error handling logic.
| name | kotlin-flow |
|---|---|
| description | Kotlin Flow - StateFlow, SharedFlow, operators, testing |
| version | "1.0.0" |
| sasmp_version | "1.3.0" |
| bonded_agent | 03-kotlin-coroutines |
| bond_type | PRIMARY_BOND |
| timeout_ms | 30000 |
| max_attempts | 3 |
| backoff | exponential |
| initial_delay_ms | 1000 |
| - name | include_examples |
| type | boolean |
| validation | "^(basics|operators|hot_flows|testing)$" |
| default | true |
| level | info |
| events | [skill_invoked, topic_loaded, error_occurred] |
Kotlin Flow Skill
Reactive programming with Kotlin Flow.
Topics Covered
Cold vs Hot Flows
// Cold Flow - starts fresh for each collector
fun loadData(): Flow<Data> = flow {
emit(fetchData())
}
// Hot Flow - shared state
private val _state = MutableStateFlow(State())
val state: StateFlow<State> = _state.asStateFlow()
Flow Operators
fun searchUsers(query: Flow<String>): Flow<List<User>> =
query
.debounce(300)
.filter { it.length >= 2 }
.distinctUntilChanged()
.flatMapLatest { term -> userRepository.search(term) }
.catch { emit(emptyList()) }
Combining Flows
val dashboard: Flow<Dashboard> = combine(
userFlow,
ordersFlow,
notificationsFlow
) { user, orders, notifications ->
Dashboard(user, orders.size, notifications.count())
}
Testing with Turbine
@Test
fun `flow emits values`() = runTest {
viewModel.state.test {
assertThat(awaitItem().isLoading).isFalse()
viewModel.load()
assertThat(awaitItem().isLoading).isTrue()
advanceUntilIdle()
assertThat(awaitItem().data).isNotNull()
}
}
Troubleshooting
| Issue | Resolution |
|---|---|
| Flow never emits | Add terminal operator (collect, first) |
| Stale data in UI | Use stateIn or shareIn properly |
Usage
Skill("kotlin-flow")