Sean Proctor
02/14/2022, 2:17 PMflow { getSubscriptionFlow().collect { emit(it) } }
would work, but it looks weird. Is there a simpler way to write that?Joffrey
02/14/2022, 2:18 PMFlow
? By that I mean what suspending stuff does it do before returning the flow, and why is that stuff not part of the flow definition?Sean Proctor
02/14/2022, 2:20 PMSean Proctor
02/14/2022, 2:21 PMephemient
02/14/2022, 2:22 PMJoffrey
02/14/2022, 2:23 PMfun yourFun(): Flow<X> = flow {
val token = fetchToken()
emitAll(getSubscriptionFlow(token))
}
Sean Proctor
02/14/2022, 2:24 PMephemient
02/14/2022, 2:27 PMFunctions returningorFlow
should return the result immediately and may start a new coroutine in the background. As a consequence, such functions should not be suspending and if they launch a coroutine in the background, they should be declared as extension functions onChannel
.CoroutineScope
Sean Proctor
02/14/2022, 2:33 PMgildor
02/14/2022, 3:08 PMgildor
02/14/2022, 3:11 PMJoffrey
02/14/2022, 3:12 PMsuspend fun <T> x(): Flow<T>
Sean Proctor
02/14/2022, 3:13 PMgildor
02/14/2022, 3:13 PMSean Proctor
02/14/2022, 3:23 PMfun observeTickets(): Flow<List<Ticket>> =
flow {
emitAll(
withClient { client ->
client.subscription().toFlow()
}
)
}
I'm happy with the result. withClient has the signature suspend fun <T> withClient((Client) -> T): T
Joffrey
02/14/2022, 3:43 PMwith
prefix in kotlin functions usually implies that the thing is provided as a receiver rather than argument. use
does provide the "thing" as argument to the lambda, on the other hand (but it implies the resource is created for the lambda and then closed after the lambda is done).
So I'd suggest either suspend fun <T> withClient(Client.() -> T): T
if there is no notion of cleanup, or suspend fun <T> useClient((Client) -> T): T
if you actually close some resources.
But that's nitpicking on style of course.Sean Proctor
02/14/2022, 3:55 PM