Kotlin 如何在RoomDb呼叫后立即取消对coroutine flows的订阅

Kotlin 如何在RoomDb呼叫后立即取消对coroutine flows的订阅,kotlin,android-room,kotlin-coroutines,kotlin-flow,Kotlin,Android Room,Kotlin Coroutines,Kotlin Flow,我试图查询房间数据库(操作1),然后根据返回的结果对同一个表执行另一个操作。但是我注意到,每次执行第二个操作时,协同程序都会查询数据库(操作1)。但这不是我想要的。举个例子: 我的项目: @Query("SELECT * FROM item_table") fun selectItems():Flow<List<Item>> @Insert suspend fun insertItem(item:Item) 但在itemDao.insertItem

我试图查询房间数据库(操作1),然后根据返回的结果对同一个表执行另一个操作。但是我注意到,每次执行第二个操作时,协同程序都会查询数据库(操作1)。但这不是我想要的。举个例子:

我的项目:

@Query("SELECT * FROM item_table")
fun selectItems():Flow<List<Item>>

@Insert
suspend fun insertItem(item:Item)

但在
itemDao.insertItem(item)
之后,它会再次显示日志消息。即使我再次从另一个方法调用
itemDao.insertItem(item)
,它也会显示日志消息。是否有任何方法可以在收取费用后立即取消预订协同计划?

您可以取消协同计划查看流程<代码>this@launch.cancel()这是否回答了您的问题?我不知道怎么用那个密码
fun insertIfListEmpty(item:Item){

    val job=CoroutineScope(IO).launch {
        itemDao.selectItems().collect{
          log.d(TAG,"items collected")
          if (it.isNullOrEmpty()) {
             itemDao.insertItem(item)
          }
        }

    }

}