kotlinkotlin-coroutinesandroid-things

Android-Things: Migrate gpiocallback functions to suspendcoroutine functions


Following the example in the photo below, I want to migrate a function with callback to a SuspendCoroutine function:

Example migration callback function to coroutine function

1) Is it possible to transpose the code below to SuspendCoroutine? (I ask why there may be reserved codes from the library, type: onGpioEdge and registerGpioCallback.

2) How can I do this?

class ButtonActivity : Activity() {
  // GPIO port wired to the button
  private lateinit var buttonGpio: Gpio
  // Step 4. Register an event callback.
  private val callback = object : GpioCallback() {
    fun onGpioEdge(gpio: Gpio): Boolean {
      Log.i(TAG, "GPIO changed, button pressed")
      // Step 5. Return true to keep callback active.
      return true
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val manager = PeripheralManager.getInstance()
    try {
      // Step 1. Create GPIO connection.
      buttonGpio = manager.openGpio(BUTTON_PIN_NAME)
      // Step 2. Configure as an input.
      buttonGpio.setDirection(Gpio.DIRECTION_IN)
      // Step 3. Enable edge trigger events.
      buttonGpio.setEdgeTriggerType(Gpio.EDGE_FALLING)
      // Step 4. Register an event callback.
      buttonGpio.registerGpioCallback(mCallback)
    } catch (e: IOException) {
      Log.e(TAG, "Error on PeripheralIO API", e)
    }
  }

  override fun onDestroy() {
    super.onDestroy()
    // Step 6. Close the resource
    if (buttonGpio != null)
    {
      buttonGpio.unregisterGpioCallback(mCallback)
      try {
        buttonGpio.close()
      } catch (e: IOException) {
        Log.e(TAG, "Error on PeripheralIO API", e)
      }
    }
  }

Solution

  • That's an interesting idea, but I'm not sure coroutines are the best fit for GPIO.

    Coroutines work great for asynchronous operations that return a value, such as API calls. GPIO is more of al listener that can happen at any time, it's a different type of callback. I would compare it to onClickListeners, and I don't think those are a good fit for coroutines either.