User_007
User_007

Reputation: 165

How to check Firebase connection for each server request? How do I reconnect?

I dont know if it is very rudimentary question. I am trying to add Firebase to my web app server side (JAVA), not an android project. My objective is to push updates to the clients for some changes to a particular entity. I am using appengine as the db. So when the entity is updated i need to push the realtime db and the clients(browser) listens for the updated node. I am trying to start off with establishing connection from java. wrote this below code. gets connected to db, but after a few seconds it gets disconnected.

  1. Should i initialize the app again?
  2. Also once it is connected to Firebase, do i have to check if the connection is still active and the push to Firebase? Does it have to be repeated for every request?
  3. Is there any better way to write this?

I highly appreciate any help. Successfully implemented with Javascript but struggling with JAVA end. Thanks in advance.

@SuppressWarnings(
        { "unchecked" , "rawtypes" } )
    public static void initiateFirebaseDB() throws FileNotFoundException
        {

            if ( FirebaseApp.getApps().isEmpty() )
                {

                    AccessController.doPrivileged( new PrivilegedAction()
                        {
                            public Object run()
                                {
                                    FileInputStream serviceAccount = null;
                                    try
                                        {
                                            serviceAccount = new FileInputStream( /* path to the json file */  );
                                        }
                                    catch ( FileNotFoundException e )
                                        {
                                            e.printStackTrace();
                                        }

                                    FirebaseOptions options = new FirebaseOptions.Builder()
                                            .setCredential( FirebaseCredentials.fromCertificate( serviceAccount ) )
                                            .setDatabaseUrl( /* db url */ ).build();
                                    FirebaseApp.initializeApp( options );

                                    return null;
                                }
                        } );
                }

            DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference( ".info/connected" );
            connectedRef.addValueEventListener( new ValueEventListener()
                {
                    @Override
                    public void onDataChange( DataSnapshot snapshot )
                        {
                            boolean connected = snapshot.getValue( Boolean.class );
                            if ( connected )
                                System.out.println( "connected" );
                            else
                                {
                                    System.out.println( "not connected" );
                                }
                        }

                    @Override
                    public void onCancelled( DatabaseError error )
                        {
                            System.err.println( "Listener was cancelled" );
                        }
                } );
        }

Upvotes: 0

Views: 1551

Answers (1)

Chad Robinson
Chad Robinson

Reputation: 4623

Tracking the connected status is mostly meant for mobile apps, and not even really for Firebase-related tasks so much as it's a great way to detect network connectivity state changes in those apps. That's often an important but tricky-to-get-right task in mobile, so this is basically Firebase providing an extra service to those devs. It isn't at all a requirement, and plenty of apps are written that never listen to this value.

The Firebase database service is meant to be treated as a "magic" singleton: you should write your code as if "it just works". Some calls do have the ability to report errors, and you should handle them where this is the case. But by and large, you shouldn't spend much/any time thinking about connectivity to the server when it comes to coding for handling data updates. Just do them, and they should work.

Firebase is also an "eventually consistent", "last write wins" database, and you should architect what you're doing around that concept. At News Rush we regularly overwrite existing values with new ones (server-side) without bothering to check if the update is required. Suppose your server node died and had to be restarted, or there was a network error and the update was dropped and not recoverable? Suppose the write was rejected because another write got there first?

Firebase provides no mechanism for determining what made it through. Writing a little more often than you think you need to can provide a measure of "self healing" to your app. Don't forget, one of Firebase's big features is massive scale/capacity. That's not a nice-to-have, it's an actual FEATURE and you should take advantage of it here.

Upvotes: 1

Related Questions