In Code A, I should use emit( Result.Success(listEntityToModel(it)) )
, and in Code B, I should use emitAll(s)
.
When do I need use emitAll instead of emit in Kotlin?
Code A
override fun listRecord(): Flow<Result<List<MRecord>>> {
return mRecordDao.listRecord().transform {
emit(Result.Loading)
emit( Result.Success(listEntityToModel(it)) )
}
}
Code B
override fun listRecord(): Flow<Result<List<MRecord>>> {
return flow {
emit(Result.Loading)
val s=mRecordDao.listRecord().map { Result.Success(listEntityToModel(it)) }
emitAll(s)
}
}
CodePudding user response:
transform
is called on each element of a parent flow. If you want to re-emit that element, the only thing you can emit is that one element.
Your Code A is kind of pointless, because it emits a Loading state presumably because you want to show in the UI that something is loading, but it immediately emits data afterwards, so there will be no time to show that loading state. And since the lambda in transform
is called on each element after it arrives, it is too late for a loading state to be useful.
In Code B, you are building a flow from scratch with the flow
builder. emitAll()
emits an entire flow instead of doing it one by one. emitAll(s)
is the same as s.collect { emit(it) }
.