Created
December 17, 2025 16:22
-
-
Save sdetilly/670dfd6252b7811e927b4468a30d8d0a to your computer and use it in GitHub Desktop.
Working with .fold
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
| data class User(val name: String) | |
| data class UserWithInterest(val user: User, val interests: List<String>) | |
| class MyRepository { | |
| private val interestsMap = mapOf( | |
| "Sarah" to listOf( | |
| "Skiing", | |
| "Bingo" | |
| ), | |
| "Tim" to listOf( | |
| "TV", | |
| "Video games" | |
| ), | |
| "John" to listOf( | |
| "Cars", | |
| "Movies", | |
| "Walking" | |
| ) | |
| ) | |
| fun fetchUsers(): Flow<List<User>> = | |
| flowOf( | |
| listOf( | |
| User("Sarah"), | |
| User("Tim"), | |
| User("John") | |
| ) | |
| ) | |
| // Simulate an API call | |
| fun fetchInterests(user: User): Flow<List<String>?> = | |
| flowOf(interestsMap[user.name]) | |
| } | |
| // Version using .fold | |
| class MyFoldUseCase { | |
| private val repository = MyRepository() // This would normally be injected! | |
| fun fetchUsers(): Flow<List<UserWithInterest>> = | |
| repository.fetchUsers() | |
| .flatMapLatest { users -> | |
| users.map { user -> | |
| repository.fetchInterests(user).map { interests -> | |
| user.toUserWithInterests(interests.orEmpty()) | |
| } | |
| }.fold(initial = flowOf(emptyList<UserWithInterest>())) { acc, flow -> | |
| acc.combine(flow) { list, userWithInterest -> | |
| list + userWithInterest | |
| } | |
| } | |
| } | |
| private fun User.toUserWithInterests(interests: List<String>) = | |
| UserWithInterest(this, interests) | |
| } | |
| // Version with Async | |
| class MyAsyncUseCase { | |
| private val repository = MyRepository() // This would normally be injected! | |
| fun fetchUsers(): Flow<List<UserWithInterest>> = | |
| repository.fetchUsers() | |
| .flatMapLatest { users -> | |
| flow { | |
| coroutineScope { | |
| val results = users.map { user -> | |
| async { | |
| val interests = repository.fetchInterests(user).first() | |
| user.toUserWithInterests(interests.orEmpty()) | |
| } | |
| }.awaitAll() | |
| emit(results) | |
| } | |
| } | |
| } | |
| private fun User.toUserWithInterests(interests: List<String>) = | |
| UserWithInterest(this, interests) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment