https://kotlinlang.org logo
#coroutines
Title
# coroutines
f

Florian

12/05/2020, 2:16 PM
Is there something wrong with the design of this method? It's both a
suspend fun
but also returns a Flow. And the first line can't be caught like this because it's not inside the Flow.
Copy code
suspend fun getChatUserFlow(uid: String): Flow<ChatUser?> {
        val results = userCollection.whereEqualTo(FieldPath.documentId(), uid).get().await()
        return if (!results.isEmpty) {
            results.documents[0].reference.asFlow<ChatUser>()
        } else {
            flowOf(null)
        }
    }
Here is my new approach, I guess this makes more sense:
Copy code
fun getChatUserFlow(uid: String): Flow<ChatUser?> =
        userCollection.whereEqualTo(FieldPath.documentId(), uid).asFlow<ChatUser>().flatMapLatest { result ->
            if (!result.isEmpty()) {
                userCollection.document(result[0].uid!!).asFlow()
            } else {
                flowOf(null)
            }
        }
g

gildor

12/06/2020, 12:24 AM
Yes, combining Flow with suspend function is usually not what you need
f

Florian

12/06/2020, 7:23 AM
Thanks, that's a useful rule of thumb 👍
4 Views