协程折叠功能和Firestore的问题

时间:2020-05-13 03:14:22

标签: firebase kotlin google-cloud-firestore kotlin-coroutines

感谢您抽出宝贵的时间阅读我的问题。

我目前正在使用Firebase Firestore检索要显示到UI的对象的对象列表,我试图使用暂停功能来折叠对象的累积值来自Firestore服务器的一系列调用,但目前我无法将结果值传递到协程范围之外。

这是我的折叠功能:

suspend fun getFormattedList(): FirestoreState {
    return foldFunctions(FirestoreModel(""), ::getMatchesFromBackend, ...., ....)
}

这是我的自定义折叠功能:

suspend fun foldFunctions(model: FirestoreModel,
    vararg functions: suspend (FirestoreModel, SuccessData) -> FirestoreState): FirestoreState {

    val successData: SuccessData = functions.fold(SuccessData()) { updatedSuccessData, function ->
            val status = function(model, updatedSuccessData)
            if (status !is FirestoreState.Continue) {
                return status
            }
            updatedSuccessData  <--- I managed to retrieve the list of values correctly here
        }

    val successModel = SuccessData() 
    successData.matchList?.let { successModel.matchList = it } 
    successData.usermatchList?.let { successModel.usermatchList = it } 
    successData.formattedList?.let { successModel.formattedList = it } 

    return FirestoreState.Success(successModel) <--- I cant event get to this line with debugger on
}

这是我的第一个功能(运行正常)

suspend fun getMatchesFromBackend(model: FirestoreModel, successData: SuccessData): FirestoreState {
        return try {
            val querySnapshot: QuerySnapshot? = db.collection("matches").get().await()

            querySnapshot?.toObjects(Match::class.java).let { list ->
                val matchList = mutableListOf<Match>()
                list?.let {
                    for (document in it) {
                        matchList.add(Match(document.away_score,
                            document.away_team,
                            document.date,
                            document.home_score,
                            document.home_team,
                            document.match_id,
                            document.matchpoints,
                            document.played,
                            document.round,
                            document.tournament))
                    }
                    successData.matchList = matchList <--- where list gets stored
                }
            }
            FirestoreState.Continue
        } catch (e : Exception){
            when (e) {
                is RuntimeException -> FirestoreState.MatchesFailure
                is ConnectException -> FirestoreState.MatchesFailure
                is CancellationException -> FirestoreState.MatchesFailure
                else -> FirestoreState.MatchesFailure
            }
        }
    }

我的假设是,取消了悬念的乐趣,并阻止了范围的延续,我尝试使用 runBlocking {} 而没有用。如果有人对如何解决此问题有所了解,我将非常感激。

0 个答案:

没有答案