Android-Things:将gpiocallback函数迁移为suspend协程函数

问题描述 投票:0回答:1

下面的示例中,我想将带有回调的函数迁移到SuspendeCoroutine函数:

Example migration callback function to coroutine function

1)是否可以将下面的代码转换为SuspendCoroutine? (我问为什么从库中可以保留代码,请输入:onGpioEdge和registerGpioCallback。

2)我该怎么办?

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)
      }
    }
  }
kotlin kotlin-coroutines android-things
1个回答
0
投票

这是一个有趣的想法,但是我不确定协程最适合GPIO。

协程非常适合返回值的异步操作,例如API调用。 GPIO是随时可能发生的所有监听器,它是一种不同类型的回调。我可以将它与onClickListeners进行比较,我也不认为它们适合于协程。

© www.soinside.com 2019 - 2024. All rights reserved.