android - Kotlin-flow:只能在协程体内调用暂停函数
问题描述
我试图了解 Kotlin Flow 如何与协程一起工作,因此我决定开发一个测试应用程序。我正在使用 MVVM + clean 架构。这是我的数据层的片段
class QuestionListRepositoryImpl(
private val localDataStore: LocalDataStore,
private val remoteDataStore: RemoteDataStore,
private val mapper: DataToDomainMapper,
private val coroutineScopes: CoroutineScopes) : GetQuestionRepository {
override suspend fun getQuestions(): Either<Failure, Flow<List<QuestionDomainModel>>> {
coroutineScopes.io.launch {
remoteDataStore.fetchQuestions().map {
localDataStore.deleteAllQuestion(). // Error is here
localDataStore.saveQuestions(it.items) // and here
}
}
val concatMapper = flow {
emitAll(localDataStore.readQuestions().map { allDataModel ->
mapper.map(allDataModel)
})
}
return Either.Right(concatMapper.distinctUntilChanged())
}
}
这是我的数据存储界面:
interface LocalDataStore {
suspend fun saveQuestions(data: List<QuestionDataModel>)
suspend fun readQuestions(): Flow<List<QuestionDataModel>>
suspend fun deleteAllQuestion()
}
interface RemoteDataStore {
suspend fun fetchQuestions(): Either<Failure, QuestionListApiResponse>
}
我在调用deleteAllQuestion()
和saveQuestions()
调用的行中的存储库中遇到问题。将光标放在 2 个函数调用中的任何一个上都会显示此错误: 只能在协程主体内调用暂停函数
谁能指出我正确的方向?我在这里想念什么?
编辑Either.map
取自评论的实施:
fun <T, L, R> Either<L, R>.map(fn: (R) -> (T)): Either<L, T> =
this.flatMap(fn.c(::right))
fun <T, L, R> Either<L, R>.flatMap(fn: (R) -> Either<L, T>): Either<L, T> =
when (this) {
is Either.Left -> Either.Left(failure)
is Either.Right -> fn(success)
}
解决方案
推荐阅读
- python - Python Selenium:如何从具有相同相对xpath的多个未定义长度的html列表中获取元素?
- javascript - Javascript:如何使用变量初始化音频文件
- java - 如何在我输入的两个数字之间打印数字?
- python - 我的错误是什么?我正在尝试部署到 heroku,但我收到 H14 作为应用程序错误。我得到“找不到该进程类型(网络)”
- python - 如何遍历数据框并将行转换为 JSON 对象
- java - 如何正确编写 hql 查询以获取数据?我一直遇到错误
- python - 如何拆分一个单词以使其与另一个单词的长度相同
- php - php如何获取所有值数组但array_values不起作用?
- java - 你如何在java中为LinkedLists实现你自己的lastIndexOf(E e)?
- r - 使用 GAM 预测纵向数据的变化,使用 R 中单个时间点的协变量分数