我是 Kotlin Flow 的新手。我想一个一个地执行一些功能,如果有任何错误就停止执行。我为此使用以下代码:
fun uploadProjectData(contactId: String, projectId: String) = flow<Resource<Boolean>> {
emit(test1(contactId, projectId))
emit(test2(contactId, projectId))
emit(test3(contactId, projectId))
}.onEach {
if (it.errorCode != 0) {
return@onEach
}
delay(0)
}.flowOn(
Dispatchers.IO
)
suspend fun test1(contactId: String, projectId: String): Resource<Boolean> {
// api call or DB operation
return responseHandler.handleSuccess(true, "test1 Successful")
}
suspend fun test2(contactId: String, projectId: String): Resource<Boolean> {
// api call or DB operation
return responseHandler.handleError(999, "test2 Unsuccessful")
}
suspend fun test3(contactId: String, projectId: String): Resource<Boolean> {
// api call or DB operation
return responseHandler.handleSuccess(true, "test2 Successful")
}
虽然 test2() 返回 999 错误代码,但执行并没有停止,它还执行了 test3()。这段代码有什么问题?如何解决?