Gli*_*pse 7 android kotlin firebase firebase-realtime-database
该应用程序执行简单的注册(使用 FirebaseAuth、FirebaseUI 和 Google Sign In)。身份验证成功后,我使用firebaseUser.userId它从实时数据库(示例位置)获取用户配置文件/users/{userId}/someUserDataIsHere。
如果实时数据库返回null该 userId 的对象,则意味着具有该 userId 的用户在实时数据库中不存在,并且是首次登录(使用使用 Google 帐户注册),因此应创建一个配置文件(或在换句话说,用户即将注册)。在其他情况下,如果 Firebase 数据库返回用户对象,应用程序将前进到主屏幕。
用户配置文件包含一些强制性数据,例如用户 ID、电子邮件和姓名。但还包含一些可选数据,例如年龄、国家/地区等,这些数据可能为空。
问题是,当用户启动应用程序并且整个身份验证过程开始时,身份验证成功后,RealtimeDatabase 会尝试获取用户配置文件(对于 FirebaseAuth 提供的 userId),但会发生错误,java.lang.Exception: Client is offline返回一个空对象,因此应用程序“认为”用户是新用户,必须插入到实时数据库中,并执行此操作(即使它在 300 毫秒前说“客户端离线”)
当它在几毫秒前对用户进行身份验证时,无法从实时数据库中获取该用户的数据(因为它处于离线状态??),并在几毫秒后设法将新的配置文件写入实时数据库,那么它是如何离线的?
它不会造成大问题,因为它将数据插入到相同的 userId 键(它在技术上执行更新),但请记住我有一些可选字段,当这种情况发生时,这些字段将被重置。从用户的角度来看,这很奇怪,因为用户输入了一些可选字段(例如年龄),并且在一段时间后它就消失了。
我必须指出最常见的用例:
我在应用程序中使用的一些依赖项 ->
implementation platform('com.google.firebase:firebase-bom:26.4.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.firebase:firebase-messaging-ktx'
implementation 'com.google.firebase:firebase-database-ktx'
implementation 'com.firebaseui:firebase-ui-auth:6.2.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1'
implementation 'com.google.android.gms:play-services-auth:19.0.0'
Run Code Online (Sandbox Code Playgroud)
另外,在应用程序启动时使用它:
FirebaseDatabase.getInstance().setPersistenceEnabled(false)
这是我得到的错误(用其他一些 GET 请求的日志更新):
2021-01-30 16:12:12.210 9157-9599/com.fourexample.oab D/PersistentConnection: pc_0 - Connection interrupted for: connection_idle
2021-01-30 16:12:12.221 9157-9599/com.fourexample.oab D/Connection: conn_0 - closing realtime connection
2021-01-30 16:12:12.221 9157-9599/com.fourexample.oab D/WebSocket: ws_0 - websocket is being closed
2021-01-30 16:12:12.224 9157-9599/com.fourexample.oab D/PersistentConnection: pc_0 - Got on disconnect due to OTHER
2021-01-30 16:12:12.372 9157-9599/com.fourexample.oab D/WebSocket: ws_0 - closed
2021-01-30 16:13:07.094 9157-9166/com.fourexample.oab I/zygote64: Debugger is no longer active
2021-01-30 16:13:08.682 9157-9599/com.fourexample.oab D/Persistence: Starting transaction.
2021-01-30 16:13:08.687 9157-9599/com.fourexample.oab D/Persistence: Saved new tracked query in 3ms
2021-01-30 16:13:08.705 9157-9599/com.fourexample.oab D/Persistence: Transaction completed. Elapsed: 22ms
2021-01-30 16:13:11.708 9157-9599/com.fourexample.oab D/PersistentConnection: pc_0 - get 1 timed out waiting for connection
2021-01-30 16:13:11.713 9157-9157/com.fourexample.oab I/RepoOperation: get for query /requests/rs falling back to cache after error: Client is offline
2021-01-30 16:13:11.715 9157-9157/com.fourexample.oab D/Persistence: Starting transaction.
2021-01-30 16:13:11.718 9157-9157/com.fourexample.oab D/Persistence: Saved new tracked query in 2ms
2021-01-30 16:13:11.726 9157-9157/com.fourexample.oab D/Persistence: Transaction completed. Elapsed: 9ms
2021-01-30 16:13:11.741 9157-9157/com.fourexample.oab E/RequestService: java.lang.Exception: Client is offline
at com.google.firebase.database.connection.PersistentConnectionImpl$2.run(PersistentConnectionImpl.java:432)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Run Code Online (Sandbox Code Playgroud)
好的,Firebase SDK 中有一个错误。
在 GitHub 上报告/打开问题,他们即将解决它。在此链接上查看更多信息
主要问题是在以下查询中使用 get().await() 挂起函数:
val dataSnapshot = firebaseRoutes.getRequestsReference(countryCode)
.orderByChild("isActive").equalTo(true)
.limitToFirst(20)
.get()
.await()
Run Code Online (Sandbox Code Playgroud)
这将随机关闭与实时数据库的连接。我想出了一个使用扩展的解决方法,直到他们最终解决为止。
因此,如果您想使用查询和暂停功能,请检查此扩展:
suspend inline fun <reified T> Query.awaitSingleValueEventList(): Flow<FlowDataState<List<T>>> =
callbackFlow {
val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
try {
val entityList = mutableListOf<T>()
snapshot.children.forEach { dataSnapshot ->
dataSnapshot.getValue<T>()?.let {
entityList.add(it)
}
}
offer(FlowDataState.Success(entityList))
} catch (e: DatabaseException) {
offer(FlowDataState.Error(e))
}
}
override fun onCancelled(error: DatabaseError) {
offer(FlowDataState.Error(error.toException()))
}
}
addListenerForSingleValueEvent(valueEventListener)
awaitClose { removeEventListener(valueEventListener) }
}
Run Code Online (Sandbox Code Playgroud)
用法:
suspend fun getActiveRequests(countryCode: String): Flow<FlowDataState<List<RequestEntity>>> {
return firebaseRoutes.getRequestsReference(countryCode)
.orderByChild("isActive").equalTo(true)
.limitToFirst(20)
.awaitSingleValueEventList()
}
Run Code Online (Sandbox Code Playgroud)
FlowDataState 只是一个可能是数据或错误的包装器
sealed class FlowDataState<out R> {
data class Success<out T>(val data: T) : FlowDataState<T>()
data class Error(val throwable: Throwable) : FlowDataState<Nothing>()
}
Run Code Online (Sandbox Code Playgroud)
调用这个:
service.getActiveRequests(countryCode).collect {
when (it) {
is FlowDataState.Success -> {
// map from entity list to domain model list
// and emit to ViewModel
}
is FlowDataState.Error -> {
// emit error to viewModel
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6481 次 |
| 最近记录: |