I'm confused as how to to plug a suspending functi...
# coroutines
u
I'm confused as how to to plug a suspending function into a flow I notice the flowOf builder, but that requires value, so that means its evaluated beforehand I'd expect something like this
Copy code
flowOf {
   someSuspendFunction()
}
am I missing something, or is it left to clients to create such extension comming from rx, I have it mapped in by brain as such
Copy code
Observable.just == flowOf(value)
Observable.fromCallable == flowOf { .. }
e
Copy code
flow { emit(someSuspendFunction()) }
u
yea but thats too much crap 😄 I'd expect it in the builders file, since it has like 20 of these, but the actual 2 you would most often use, one is missing?
so I created the
Copy code
fun <T> flowOf(action: suspend () -> T): Flow<T> {
    return flow { emit(action()) }
}
but imports get messed up if I need something like this
Copy code
foo
.flatMapLatest {
    if (!it) {
        flowOf(Uninitialized)
    } else {
        my.package.name.flowOf { repository.syncDocuments() }
    }
}
obviously thats a naming issue but .. still odd design choice
e
you could name it
flowOf
and import both, but seems like a bad idea to me, due to overload resolution
u
btw what's this one?
Copy code
@FlowPreview
public fun <T> (suspend () -> T).asFlow(): Flow<T> = flow {
    emit(invoke())
}
Copy code
{ repository.syncDocuments() }                          .asFlow()
complains
Suspension functions can be called only within coroutine body
e
type inference isn't smart enough, maybe
perhaps one of
Copy code
val lambda: suspend () -> Unit = { repository.syncDocuments() }
lambda.asFlow()
or
repository::syncDocuments.asFlow()
u
yea function reference works but thats just a coincidence it has no params
u
yea, well
Copy code
suspend { repository.syncDocuments() }
                            .asFlow()
that suspend literal is news to me
a
a one emit and close flow is better modeled as a
suspend fun
that returns a value instead
u
yea I know, its Flow logic, just need essentially this
observable.switchMap { single.toObservable() }
the toObservable extension
a
isn't that the same as
Copy code
flow.mapLatest { mySuspendFun(it) }
?
u
not sure, im new, esentially I was looking for
flowOf(suspend { ...})
I never knew of the syntax a builder function
a
In cases where you need flow with single object can be solved like this
Copy code
foo
.flatMapLatest {
    flow {
        if (!it) {
            emit(Uninitialized)
        } else {
            emitAll(repository.syncDocuments())
        }
    }
}
👍 1
e
Since you're used to Rx, you might know https://rxmarbles.com/ Likewise, there is https://flowmarbles.com/