I'm trying to execute some code after calling collect on a Flow<MyClass>. I'm still kind of new to using Flows so I don't understand why the code after the function doesn't get called.

我如何使用流程:

incidentListener = FirebaseUtils.databaseReference
                      .child(AppConstants.FIREBASE_PATH_AS)
                      .child(id)
                      .listen<MyClass>() //This returns a Flow<MyClass?>?

How I consume the Flow:

private suspend fun myFun() {
   viewmodel.getListener()?.collect { myClass->
       //do something here
   }
   withContext(Dispatchers.Main) { updateUI() } //the code never reaches this part
}

How myFun() is called:

CoroutineScope(Dispatchers.IO).launch {
   myFun()
}

就我试图让它工作而言,我试图关闭协同程序上下文,但没有成功.我假设流的工作方式不同于常规的协同程序.

Update:

我正在使用这段代码通过Firebase进行监听.我不知道它是否有用,但也许是我实现它的方式导致了这个问题?

inline fun <reified T> Query.listen(): Flow<T?>? =
callbackFlow {
    val valueListener = object : ValueEventListener {
        override fun onCancelled(databaseError: DatabaseError) {
            close()
        }

        override fun onDataChange(dataSnapshot: DataSnapshot) {
            try {
                val value = dataSnapshot.getValue(T::class.java)
                offer(value)
            } catch (exp: Exception) {
                if (!isClosedForSend) offer(null)
            }
        }
    }
    addValueEventListener(valueListener)
    awaitClose { removeEventListener(valueListener) }
}

推荐答案

我忘了发我自己的答案.我以前发现过这个问题.那是因为我没有退回Coroutine Context美元.

My code has been updated since but with the code above as an example it should be written as follows:

private suspend fun myFun() {
   viewmodel.getListener()?.collect { myClass->
       //do something here
       return@collect
   }
   withContext(Dispatchers.Main) { updateUI() return@withContext } 
   //the code should flow downwards as usual
}

Kotlin相关问答推荐

API迁移到Spring Boot 3后,Spring Security无法工作

为什么onEach不是挂起函数,而Collect是?

多模块Kotlin项目中的FreeFair

我可以更改方法中泛型类的类型参数边界吗?

在 Compose 中使用 Text() 时如何获取文本的大小?

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

为什么 KFunction2 在 Kotlin 中不是可表示类型?

如何将字符串格式化为电话号码kotlin算法

Kotlin 日期格式从一种更改为另一种

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

Kotlin - 创建指定长度的随机整数的 ArrayList?

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

如何在 Kotlin 中创建一个打开新活动(Android Studio)的按钮?

Ktor 在 java.library.path 中没有 netty_transport_native_epoll_x86_64

Kotlin中的测试无法访问受保护(protected)的方法

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

如何在特定条件下清除jetpack数据存储数据

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用

如何在不绑定ViewModel(MVVM)中的UI的情况下使用android导航?