Using Android Jetpack LiveData provides some advantages that simplify the developer experience: updates are done through an Observer which handles the lifecycle of an associated UI component, thus avoiding crashes if it is in background, memory leaks, etc.
In Webcom SDK for Android, LiveData can be used to get data content, or to get the user's authentication status:
Data subscriptions
Subscriptions to data on a node can be done either using a callback (see Callbacks) or using LiveData.
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"
val livedata = manager.node(path).subscribe(Value.Changed::class)
livedata.observe(this, object : androidx.lifecycle.Observer<Notification<Value.Changed>> {
override fun onChanged(event: Notification<Value.Changed>) {
when (event) {
is Notification.DataNotification -> runOnUiThread { // post the code that updates the UI on the main thread
binding.button.isEnabled = it.data.value.asBoolean
}
else -> { livedata.removeObserver(this) } // the subscription was stopped (either canceled or revoked)
}
}
})
Authentication subscriptions
The user's authentication status can be watched either using a callback (see auth-state.md) or using LiveData. For example, the display of a dialog showing the user's authentication status can be implemented this way:
import com.orange.webcom.sdk.authentication.AuthenticationEvent
val myApp = WebcomApplication.default // the app defined by the 'webcom.properties' asset file
val authentication = myApp.authenticationService
val livedata = authentication.subscribe()
livedata.observe(this, object : androidx.lifecycle.Observer<AuthenticationEvent> {
override fun onChanged(event: AuthenticationEvent) {
if (evt is AuthenticationState.Authenticated) {
runOnUiThread {
AlertDialog.Builder(context)
.setTitle("Welcome " + evt.details.displayName)
.show()
}
}
}
})