我有一种方法可以检查列表是否包含用户。由于某种原因它总是返回 false,即使用户位于列表中。该函数确实有效,我知道它确实找到了用户,只是不确定为什么它不返回任何其他内容,但false
.
我知道它有效,因为我有另一种方法使用此代码片段来检查用户是否在列表中并删除或添加它们。这很有效,所以我知道它正在拉列表。
Method:
fun checkUserChatChannel(channelId: String): Boolean {
var list = mutableListOf<String>()
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
var bool = false
chatChannelsCollectionRef.document(channelId).get().addOnSuccessListener {
if (it.exists()) {
list = it.get("userIds") as MutableList<String>
if(list.contains(currentUserId)){
bool = true
}
}
}
return bool
}
Calling:
boolean inOut = FirestoreUtil.INSTANCE.checkUserChatChannel(moduleId);
if(!inOut)
{
JLChat.setText("Join");
}
else
{
JLChat.setText("Leave");
}
但该按钮将始终保持在“加入”状态:
这是我使用的另一种方法,所以我知道代码可以从列表中删除用户(与问题无关):
fun LeaveGroup(channelId: String) {
currentUserDocRef.collection("engagedChatChannels").document(channelId)
.delete()
var list = mutableListOf<String>()
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
chatChannelsCollectionRef.document(channelId).get().addOnSuccessListener {
if (it.exists()) {
list = it.get("userIds") as MutableList<String>
if(list.contains(currentUserId)){
list.remove(currentUserId)
}
}
val newChannel = chatChannelsCollectionRef.document(channelId)
newChannel.set(GChatChannel(channelId,list))
}
}
Firebase API 是asynchronous
, 意思是onSucces()
函数被调用后立即返回,并且回调Task
它返回,稍后将被调用。无法保证需要多长时间。因此,可能需要几百毫秒到几秒的时间才能获得数据。因为该方法立即返回,所以您的值bool
您尝试返回的变量尚未从回调中填充。
基本上,您尝试从异步 API 同步返回值。这不是一个好主意。您应该按预期异步处理 API。
解决这个问题的一个快速方法是使用您的值bool
多变的only在回调里面。这也意味着你需要改变你的checkUserChatChannel
而不是返回布尔值以返回 void,否则我建议您从中查看我的答案的最后部分post其中我解释了如何使用自定义回调来完成此操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)