Most of the functions provided by the Webcom SDK for Android take callback functions in order to execute asynchronous
work. Typically, when subscribing to data changes (see the “Subscribing to changes” chapter) with
the subscribe
function, the passed
callback
function is called further each time the subscribed data changes, as long as the subscription is not
canceled.
When using such functions, you must be aware that all callbacks are actually executed by the SDK on a dedicated
thread, which is independent of the Android main thread. As a consequence, you can (and must) not act on the
UI directly from the code of these callback functions, otherwise your app is likely to scratch. If you need to
update the UI from a callback function, you must wrap the corresponding code using the
runOnUiThread
method provided
by the Android API.
For example, imagine that a button must be enabled or disabled depending on a boolean value stored within the Webcom database. This can be implemented this way:
import com.orange.webcom.sdk.datasync.subscription.SubscribableEvent.*
val myApp = WebcomApplication.default // the app defined by the 'webcom.properties' asset file
val datasync = myApp.datasyncService // this service is the entry point for all datasync-related features
val manager = datasync.createManager()
val path = "/some/path/to/watch"
manager.node(path).subscribe(Value.Changed::class) {
// this code will be executed on a dedicated thread of the SDK
when (it) {
is Notification.DataNotification -> runOnUiThread { // post the code that updates the UI on the main thread
binding.button.isEnabled = it.data.value.asBoolean
}
else -> { /* do nothing */ } // the subscription was stopped (either canceled or revoked)
}
}