Skip to content

Instantly share code, notes, and snippets.

@sdetilly
Created December 17, 2025 16:22
Show Gist options
  • Select an option

  • Save sdetilly/670dfd6252b7811e927b4468a30d8d0a to your computer and use it in GitHub Desktop.

Select an option

Save sdetilly/670dfd6252b7811e927b4468a30d8d0a to your computer and use it in GitHub Desktop.
Working with .fold
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