android - 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 {
}
}
}
解决方案
取决于你想要做什么但不太熟悉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)
}
甚至Flow
与callbackFlow
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/callback-flow.html一起使用
推荐阅读
- docusignapi - 如何为没有电子邮件和姓名的收件人获取嵌入式签名 URL
- python - Python Launcher:默认运行意外版本的 Python
- file-upload - MVC 5 文件上传
- python - Python Web Scraping:如何获取内部站点的 HTML
- python - Flask 中的用户身份验证 - 如何在函数中实现?
- java - JDA - 机器人听取其他机器人的反应
- python - 从 S3 存储桶中读取大量 CSV 文件
- ios - 使用委托在两个以上视图控制器之间传递数据
- python - 有什么方法可以正确合并熊猫中具有不同暗度的两个时间序列?
- c - C 意外标识符 - For 循环增量