Tutorial: Get connection state

Tips and Tricks Get connection state

Webcom connection state

By default, the Webcom SDK manages a cache of sent and received data in order to manage disconnections. It is possible to force connection/disconnection and know the current connection status.

In JavaScript, use the connect() and disconnect() methods on the DatasyncService object to force connection or disconnection. You can also subscribe to the ".info/connection/connected" virtual node to be notified of changes of the connection status (replace “<your-app>” with your actual application identifier):

const myNs = new Webcom("<your-app>");
myNs.child(".info/connection/connected").on("value", snapshot => {
  const eventDate = Date.now();
  const connected = snapshot.val();
  if (connected) {
    // Connected to Webcom server (page loaded, goOnline call ...)
  } else {
    // Disconnected from Webcom server (network lost, goOffline called ...)
  }
});
myNs.datasync.disconnect(); // disconnect the websocket of the Datasync service
// ...
myNs.datasync.connect(); // reconnect the websocket of the Datasync service

In Kotlin, set the isConnectionEnabled property of the DatasyncService to true or false in order to force connection or disconnection. The actual connection state is given by the isConnected() method of the DatasyncState, which may be subscribed to using the subscribeToStateChange() method of the DatasyncManager class:

import com.orange.webcom.sdkv2.datasync.subscription.DatasyncState.ConnectionState.*

val app = WebcomApplication.default
val datasync = app.datasyncService
val manager = datasync.createManager()
manager.subscribeToStateChange { // it: DatasyncState
  println("the Datasync service is now ${if (it.isConnected()) "connected" else "disconnected"}")
}
datasync.isConnectionEnabled = false // disconnect the websocket of the Datasync service
// ...
datasync.isConnectionEnabled = true // reconnect the websocket of the Datasync service
let datasyncManager = Webcom.defaultApplication.datasyncService.createManager()
datasyncManager.subscribeToStateChange { state in
    if state.isConnected {
        print("Connected to Webcom server")
    } else {    
        print("Disconnected from Webcom server")
    }
}

Warning: on application loading, connection may take some time to establish and thus the first call to the callback may indicate that connection is down. A short time later, as soon as the connection establishment is successfully completed, the callback is called again indicating the connection is up.