I have 2 questions about `stateIn`. 1. Is this a bad approach: ```// presenter/viewmodel: val mySta...
l
I have 2 questions about
stateIn
. 1. Is this a bad approach:
Copy code
// presenter/viewmodel:

val myState: StateFlow<MyState> = api.subscribeToFlow()
  .map {..}
  .stateIn(scope = mainScope + Dispatcher.Default, started = SharingStarted.Lazily, initalValue = MyState.Initial)

// somewhere else:
fun subscribeToFlow(): Flow<Int> {
  println("thread: ${Thread.currentThread()}.") // prints main thread
  ...
  return someFlow()
}
I'm asking because the call to
api.subscribeToFlow()
runs in main thread and I don't know how to make it switch to a default thread. I could wrap everything in
withContext()
in my
subscribeToFlow()
function but is there an alternative? This brings me to my 2nd question. 2. What is a use case for the overloaded
suspend stateIn(scope: CoroutineScope)
function? It requires to be called from a suspension function while the simple
stateIn
function does not.
j
What matters is not the thread on which
subscribeToFlow
is called, but the thread/dispatcher on which collection occurs, or any context changes in the flow stream. You're doing neither in
subscribeToFlow
. And you're already switching to the default dispatcher with
stateIn
, so you're all set. According to the
stateIn
docs
Starts the upstream flow in a given scope ...
So the flow upstream of
map
should run on the default dispatcher. Verify by putting an
onEach
upstream of
map
and see what thread is being used. The flow is constructed on the main thread, true; but it doesn't run (i.e. it is not started) on the main thread.