Extension Class 中的Coroutine Channel 不发送或接收数据
Coroutine Channel in Extension Class does not send or receive data
我最近一直在使用 kotlin 和协程,我正在尝试在片段 Class 的扩展 class 中实现一个通道。为了更好地解释我自己:
MapFragment.kt --> 片段 Class 单击按钮时调用函数 sendFunction() 和 receiveFunction()。
MapFunctionality.kt --> 扩展 MapFragment class。这里实现了 sendFunction() 和 receiveFunction() 这两个函数。
MapFragment.kt
open class MapFragment : Fragment(), PermissionsListener, OnMapReadyCallback {
override fun onResume() {
super.onResume()
mymapView.onResume()
toggleButton.setOnClickListener {
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
}
}
}
MapFunctionality.kt
class MapFunctionality : MapFragment(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
private val getAllPointsChannel = Channel<MutableList<Point>>()
fun sendFunction(){
launch(coroutineContext) {
testChannel.send("Hello")
println("Message sent")
}
}
fun receiveFun(){
launch(coroutineContext) {
println("about to receive a message")
val a = testChannel.receive()
println("$a")
}
}
输出将只是
"about to receive a message"
如果我实现 MapFragment.kt class 中的功能,那么它工作正常。
知道问题出在哪里吗?
提前致谢。
从您的代码看来,您将 MapFunctionality
class 实例化了两次,这意味着您最终会得到两个实例,每个实例都有自己的 Channel
.
以下是否正确?
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
我认为你应该这样做:
val mapfun = MapFunctionality()
mapfun.receiveFun()
mapfun.sendFunction()
我最近一直在使用 kotlin 和协程,我正在尝试在片段 Class 的扩展 class 中实现一个通道。为了更好地解释我自己:
MapFragment.kt --> 片段 Class 单击按钮时调用函数 sendFunction() 和 receiveFunction()。
MapFunctionality.kt --> 扩展 MapFragment class。这里实现了 sendFunction() 和 receiveFunction() 这两个函数。
MapFragment.kt
open class MapFragment : Fragment(), PermissionsListener, OnMapReadyCallback {
override fun onResume() {
super.onResume()
mymapView.onResume()
toggleButton.setOnClickListener {
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
}
}
}
MapFunctionality.kt
class MapFunctionality : MapFragment(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
private val getAllPointsChannel = Channel<MutableList<Point>>()
fun sendFunction(){
launch(coroutineContext) {
testChannel.send("Hello")
println("Message sent")
}
}
fun receiveFun(){
launch(coroutineContext) {
println("about to receive a message")
val a = testChannel.receive()
println("$a")
}
}
输出将只是
"about to receive a message"
如果我实现 MapFragment.kt class 中的功能,那么它工作正常。
知道问题出在哪里吗?
提前致谢。
从您的代码看来,您将 MapFunctionality
class 实例化了两次,这意味着您最终会得到两个实例,每个实例都有自己的 Channel
.
以下是否正确?
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
我认为你应该这样做:
val mapfun = MapFunctionality()
mapfun.receiveFun()
mapfun.sendFunction()