kotlin - Android-Things:迁移gpiocallback函数以暂停协程函数

标签 kotlin kotlin-coroutines android-things

下面的示例中,我想将带有回调的函数迁移到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)
      }
    }
  }

最佳答案

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

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

关于kotlin - Android-Things:迁移gpiocallback函数以暂停协程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61325781/

相关文章:

kotlin - 如何确保清除由ktor Websocket客户端创建的所有Kotlin协程?

android - 如何在 Android Things 上请求权限?

Android things +(Raspberry Pi 3 模拟器和 BreadBoard 模拟器)

java - 每次应用程序来自 android 中的后台时启动第一个屏幕

kotlin - 安卓 : unit testing of LiveData and Flow

android - 在 Kotlin 中是否有更干净的方法来设置日期时间

android - 为 liveData kotlin 构建器函数指定现有的 LiveData 对象

android - 使用 nrf52840-Dongle 和 Android Things 创建 LowPAN 网络

kotlin - Kotlin Coroutine 的 block.startCoroutine() 是如何工作的?

intellij-idea - 传播运算符函数调用歧义