首页 > 解决方案 > 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)
    }

标签: androidkotlin-coroutinesandroid-mvvmclean-architecturekotlin-flow

解决方案


推荐阅读