Look for the very basic term for a certain callback

Viewed 55

I am coming from the embedded world and I am quite new to Kotlin. I know there is some mechanism I can inherit and use in my class, but I don't know the name exactly for this mechanism for Android.

What I am looking for is:

  1. I have my Activity and this one instantiates my CustomClass
  2. My CustomClass perform some background tasks like handling BLE asynchronous communication
  3. CustomClass does not know when some packets will be received.
  4. Once the package is received, the CusomClass should call back the Activity and give the data by means of this mechanism.

What would be the best option to perform these callbacks?

P.s.: My apologies, I looked extensively but I don't even know the name to start my search.

2 Answers

You can use LiveData for this purpose. essentially its an observable data holder, so when you change its data all of its obsrevers get notified. this enables you to write reactive code and reduce tightly coupled logic. its also lifecycle aware, so your activity only gets notified if its active.

A general idea would be to do following

In your CustomClass declare a LiveData object

class CustomClass{
   // Declare a LiveData object, use any type you want String, Int etc
   val myData: MutableLiveData<String> = MutableLiveData("")

   private fun onBleNotification(notification: String){
       // post to live data, this will trigger all the observers
       myData.postValue(notification)
   }

   ...
}

In your Activity, observe the LiveData object

onCreate(savedInstanceState: Bundle?){
...

    customClass.myData.observe(this, androidx.lifecycle.Observer{
        //Do anything with received command, update UI etc
    })
}
Related