首页 > 解决方案 > Firestore上的Android协程?

问题描述

我正在尝试在 APP 中实现 SOLID 原则。关于每个类的单一职责,协程可以和firebase firestore?如果是,ViewModel查询完成后如何在里面收听?

例子:

class CampaignsViewModel @ViewModelInject constructor(
    private val greenService: GreenService,
    @Assisted private val savedStateHandle: SavedStateHandle
): ViewModel() {

    fun getCampaigns() {
        greenService.getCampaigns()
    }
}


class GreenServiceImpl @Inject constructor(
    private val db: FirebaseFirestore,
) : GreenService {

    override fun getCampaigns() {
        db.collection(FirestoreDatabases.CAMPAIGNS.name)
            .get()
            .addOnSuccessListener {
                for (document in it) {
                    Log.d(BuildConfig.BUILD_TYPE, "${document.id} => ${document.data}")
                }
            }
            .addOnFailureListener {

            }
    }

}

标签: androidkotlin-coroutinessolid-principles

解决方案


取决于你想要做什么但不太熟悉firestore api你可以做这样的事情我相信

GreenServiceImpl

suspend fun getCampaigns() = withContext(Dispatchers.IO){
    val task = db.collection(FirestoreDatabases.CAMPAIGNS.name).get()
    val result = Tasks.await(task)
    //Do something with the task result
}

然后在 vour ViewModel

fun getCompaings(){
    viewModelScope.launch {
        greenService.getCampaigns()
   }
}

根据需要进行调整,但大致了解您可以做什么。

suspendCoroutine如果您想退货,也可以使用

suspend fun getCampaigns():SomeResult? = suspendCoroutine{
    val task = db.collection(FirestoreDatabases.CAMPAIGNS.name).get()
    val result = Tasks.await(task)
    it.resume(result)
}

甚至FlowcallbackFlow https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/callback-flow.html一起使用


推荐阅读