Skip to content

RealtimeDatabase randomly closes connection - Connection interrupted for: connection_idle #2385

Closed

Description

@UkiUros

Step 2: Describe your environment

  • Android Studio version: 4.1.1
  • Firebase Component: Database
  • Component version: 19.6.0

Step 3: Describe the problem

App randomly loses connection with Realtime Database before trying to get some data from it. When the issue occurs, restarting the app solves the problem but it is annoying for the users. Reproduced on Samsung S10+ (Android 10) and Nexus 5X (Android 8.1).
The strange thing is when get() call fails and the app tries to write something into the Realtime Databases, right away, the set call works.

Steps to reproduce:

It happens randomly, like 3 out of 10 app starts or GET calls.
Log:

2021-01-30 16:12:12.210 9157-9599/rs.fourexample.oab D/PersistentConnection: pc_0 - Connection interrupted for: connection_idle
2021-01-30 16:12:12.221 9157-9599/rs.fourexample.oab D/Connection: conn_0 - closing realtime connection
2021-01-30 16:12:12.221 9157-9599/rs.fourexample.oab D/WebSocket: ws_0 - websocket is being closed
2021-01-30 16:12:12.224 9157-9599/rs.fourexample.oab D/PersistentConnection: pc_0 - Got on disconnect due to OTHER
2021-01-30 16:12:12.372 9157-9599/rs.fourexample.oab D/WebSocket: ws_0 - closed
2021-01-30 16:13:07.094 9157-9166/rs.fourexample.oab I/zygote64: Debugger is no longer active
2021-01-30 16:13:08.682 9157-9599/rs.fourexample.oab D/Persistence: Starting transaction.
2021-01-30 16:13:08.687 9157-9599/rs.fourexample.oab D/Persistence: Saved new tracked query in 3ms
2021-01-30 16:13:08.705 9157-9599/rs.fourexample.oab D/Persistence: Transaction completed. Elapsed: 22ms
2021-01-30 16:13:11.708 9157-9599/rs.fourexample.oab D/PersistentConnection: pc_0 - get 1 timed out waiting for connection
2021-01-30 16:13:11.713 9157-9157/rs.fourexample.oab I/RepoOperation: get for query /bloodRequests/rs falling back to cache after error: Client is offline
2021-01-30 16:13:11.715 9157-9157/rs.fourexample.oab D/Persistence: Starting transaction.
2021-01-30 16:13:11.718 9157-9157/rs.fourexample.oab D/Persistence: Saved new tracked query in 2ms
2021-01-30 16:13:11.726 9157-9157/rs.fourexample.oab D/Persistence: Transaction completed. Elapsed: 9ms
2021-01-30 16:13:11.741 9157-9157/rs.fourexample.oab E/BloodRequestService: 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)

Relevant Code:

Some of the Queries this occurs

// BloodRequestService.kt
val dataSnapshot = firebaseRoutes.getBloodRequestsReference(countryCode)
                .orderByChild("isActive").equalTo(true)
                .limitToFirst(20)
                .get()
                .await()

// UserService.kt
val dataSnapshot = firebaseRoutes.getUsersReference()
                .orderByKey()
                .equalTo(userId)
                .limitToFirst(1)
                .get()
                .await()

Dependencies

    // firebase
    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'

    // google stuff
    implementation 'com.google.android.gms:play-services-auth:19.0.0'

Activity

  1. dimiitpk commented on Jan 31, 2021

    @dimiitpk

    I had the same problem with that and just take "await" off
    As I saw await is made for Tasks, but in Realtime Database are Query objects with EventListeners.
    So I came with a solution for SingleEventValue Queries, and problems stopped

    
    suspend inline fun <reified T> Query.awaitQueryValue() : T = suspendCancellableCoroutine { continuation ->
        addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                snapshot.getValue<T>()?.let { instance ->
                    continuation.resume(instance)
                }
            }
            override fun onCancelled(error: DatabaseError) {
                continuation.resumeWithException(Throwable(error.message))
            }
        })
    }
    
  2. UkiUros commented on Jan 31, 2021

    @UkiUros
    Author

    Hi @dimiitpk,

    thank you for the code snipped, will try this for sure. Could you, please, elaborate on how you use this?

    val dataSnapshot = firebaseRoutes.getUsersReference()
                    .orderByKey()
                    .equalTo(userId)
                    .limitToFirst(1)
                    .awaitQueryValue<UserEntity>()
    

    It would be something like this?
    Not sure if it's gonna cover my case, I will probably need to modify this a little bit. If I am not wrong, the query always returns data snapshot containing list.

  3. dimiitpk commented on Jan 31, 2021

    @dimiitpk

    @UkiUros
    pozdrav za balkan :)

    This is the way I am using it. I am just using it for Single Item value, no lists. If u try with lists, give me feedback, buy I think its going with ".children" on snapshot...

    override suspend fun getVenueFromBooking(venueId: String) =
            database
                .child(VENUES_COLLECTION)
                .child(venueId)
                .awaitQueryValue<VenueRemote>()
                .let {
                    venueMapper.mapFromEntity(it)
                }
    
  4. UkiUros commented on Jan 31, 2021

    @UkiUros
    Author

    @dimiitpk pozdrav :D

    Okay, I see, so you are accessing your data directly. Thanks 👍

    Update: Tried your solution for lists but it does not work. Even if I modified it to support lists, it returns the following - {key = users, value = null}

    It's like not waiting for the queries at all, callback fires almost immediately

  5. UkiUros commented on Feb 3, 2021

    @UkiUros
    Author

    As @dimiitpk mentioned earlier, await() is causing some problems which lead to randomly disconnecting from Firebase DB. When I implemented a different solution (as shown below) to support Kotlin Coroutines, the problem with "Client is offline" stopped.

    Here you go my Query extension for handling lists of data with SingleValueEvent:

    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) }
        }
    

    FlowDataState is nothing but a wrapper that could be Data or Error

    sealed class FlowDataState<out R> {
        data class Success<out T>(val data: T) : FlowDataState<T>()
        data class Error(val throwable: Throwable) : FlowDataState<Nothing>()
    }
    

    Using it in my service class (RequestService.kt):

        suspend fun getActiveRequests(countryCode: String): Flow<FlowDataState<List<RequestEntity>>> {
            return firebaseRoutes.getRequestsReference(countryCode)
                .orderByChild("isActive").equalTo(true)
                .limitToFirst(20)
                .awaitSingleValueEventList()
        }
    

    And finally, in my RequestRepository.kt, within another suspend function:

    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
                   }
               }
           }
    
  6. schmidt-sebastian commented on Feb 4, 2021

    @schmidt-sebastian
    Contributor

    Thanks for letting us know. If you are using addValueEvent listeners, does this issue still occur?

  7. UkiUros commented on Feb 4, 2021

    @UkiUros
    Author

    @schmidt-sebastian
    I didn't try it with addValueEventListener. Just need to read data once, hence I used singleValueEvent in my extension. The issue is no longer occurring since I am using that approach.

    Using someQuery.get().await() to read data (like fetching user data from user node, via query) did cause me troubles occasionally, as mentioned earlier in the comments (please check logs).

  8. dimiitpk commented on Feb 5, 2021

    @dimiitpk

    @schmidt-sebastian

    Thanks for letting us know. If you are using addValueEvent listeners, does this issue still occur?

    So u can do this, it's working in my code, and clearing listener is done for u, connected with ViewModel or any lifecycle

    fun getBookingss(upcoming: Boolean, role: String) =
        callbackFlow<Resource<List<BookingRemote>>> {
            sendBlocking(Resource.loading(null))
    
            val query = Firebase.database
                .reference
                .child(Constants.BOOKING_COLLECTION)
                .orderByChild(Constants.BOOKING_UID_USER_CHILD)
                .equalTo("dskadoasd")
    
            val listener = object : ValueEventListener {
                override fun onCancelled(error: DatabaseError) {
                    [email protected](Resource.error(error.message, null))
                }
    
                override fun onDataChange(dataSnapshot: DataSnapshot) {
                    val items = dataSnapshot.children.mapNotNull {
                        it.getValue(BookingRemote::class.java)
                    }
                    [email protected](
                        Resource.success(
                            items
                        )
                    )
                }
            }
            query.addValueEventListener(listener)
    
            awaitClose {
                query.removeEventListener(listener)
            }
        }
    
  9. schmidt-sebastian commented on Feb 5, 2021

    @schmidt-sebastian
    Contributor

    I am pretty sure I have a fix for this: #2414

  10. locked and limited conversation to collaborators on Mar 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions