Is there a better way to do this? The goal is for ...
# coroutines
a
Is there a better way to do this? The goal is for the assignment to
items
to not block the thread: •
daggerLazyPagerFactory
is
dagger.Lazy, get()
bocks the thread in my case • i have the
flow { }
builder just with a single
emitAll
, which seems wrong, but moves the blocking
get()
to
Dispatcher.Default
Copy code
val items: Flow<PagingData<Item>> = flow {
        emitAll(daggerLazyPagerFactory.get().flow())
    }.flowOn(Dispatchers.Default)
        .cachedIn(viewModelScope)
If I try this, get() blocks the thread, as
flowOn{}
does not impact that:
Copy code
val items = daggerLayPagerFactory.get()
   .flow()
   .flowOn(Dispatchers.Default)
   .cacheIn(...)
r
Don't see anything wrong with this, it's kind of a common pattern when you need to do async init for the flow (definitely much better than the dreaded suspend funs which return flow)
You may prefer to rearrange things to make it clearer you're doing async init:
Copy code
flow {
     val pager = withContext(Dispatchers.Default) {
       daggerLazyPagerFactory.get()
     }
     emitAll(pager.flow())
    }
And then you won't need
flowOn
a
Thanks! TIL you can do
withContext
in
flow{ }
builder as long as you don’t emit anything in its block, I though this violated the context preservation policy. Also thanks for the heads up about dreaded suspend funs returning flows, if its a bad I idea I will come up with it eventually 😆