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

Ahmed Ibrahim

04/14/2020, 6:12 PM
Any idea why this code is not returning? It keeps suspended forever
Copy code
userRepository.streamUser().filterLoggedIn().firstOrNull()
The repository returns a Logged Out user, but I'm only interested in logged in users, I would expect that since this flow becomes an empty flow, then
firstOrNull
should return null, right or am I missing something?
z

zak.taccardi

04/14/2020, 6:13 PM
filterLoggedIn()
doesn’t emit anything, and doesn’t complete, so
firstOrNull()
won’t emit IIRC
a

Ahmed Ibrahim

04/14/2020, 6:14 PM
Copy code
fun Flow<UserResult>.filterLoggedIn(): Flow<UserResult.LoggedIn> =
    filterIsInstance()
That's the implementation of it, it is just a mere
filterIsInstance
o

octylFractal

04/14/2020, 6:14 PM
it would rely on
streamUser()
completing, otherwise how would it know if it's empty?
👍 1
a

Ahmed Ibrahim

04/14/2020, 6:19 PM
Yeah, you are right, the key is on the completion of the flow. I changed the code to
Copy code
userRepository.streamUser().take(1).filterLoggedIn().firstOrNull()
and it is working as expected, thanks everyone.
z

zak.taccardi

04/14/2020, 6:19 PM
userRepository.streamUser().firstOrNull { .. }
you can use a custom predicate IIRC
o

octylFractal

04/14/2020, 6:20 PM
as I understand that would have the same issue
z

zak.taccardi

04/14/2020, 6:20 PM
oh, yeah
🤦
3 Views