Android 扩展类中的协同路由通道不发送或接收数据
我最近一直在使用kotlin和协同程序,我正在尝试在片段类的扩展类中实现一个通道。为了更好地解释我自己: MapFragment.kt-->Fragment类,单击按钮时调用函数sendFunction()和receiveFunction() MapFunctionary.kt-->扩展了MapFragment类。下面是已实现的函数sendFunction()和receiveFunction() MapFragment.ktAndroid 扩展类中的协同路由通道不发送或接收数据,android,kotlin,kotlin-coroutines,Android,Kotlin,Kotlin Coroutines,我最近一直在使用kotlin和协同程序,我正在尝试在片段类的扩展类中实现一个通道。为了更好地解释我自己: MapFragment.kt-->Fragment类,单击按钮时调用函数sendFunction()和receiveFunction() MapFunctionary.kt-->扩展了MapFragment类。下面是已实现的函数sendFunction()和receiveFunction() MapFragment.kt open class MapFragment : Fragment()
open class MapFragment : Fragment(), PermissionsListener, OnMapReadyCallback {
override fun onResume() {
super.onResume()
mymapView.onResume()
toggleButton.setOnClickListener {
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
}
}
}
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")
}
}
映射功能.kt
open class MapFragment : Fragment(), PermissionsListener, OnMapReadyCallback {
override fun onResume() {
super.onResume()
mymapView.onResume()
toggleButton.setOnClickListener {
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
}
}
}
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")
}
}
类映射功能:MapFragment(),CoroutineScope{
覆盖val coroutineContext:coroutineContext
get()=Dispatchers.Main
private val getAllPointsChannel=Channel()
函数(){
启动(coroutineContext){
testChannel.send(“你好”)
println(“已发送消息”)
}
}
娱乐接受娱乐{
启动(coroutineContext){
println(“即将收到消息”)
val a=testChannel.receive()
println($a)
}
}
输出结果将是正确的
“即将收到消息”
如果我在MapFragment.kt类中实现这些函数,那么它就可以正常工作
你知道问题出在哪里吗
提前感谢。从您的代码来看,您好像实例化了两次
MapFunctional
类,这意味着您将得到两个实例,每个实例都有自己的频道
下面的答案正确吗
MapFunctionality().receiveFun()
MapFunctionality().sendFunction()
我认为你应该这样做:
val mapfun = MapFunctionality()
mapfun.receiveFun()
mapfun.sendFunction()
1.为什么使用默认值调度程序而不是Main
?2.使用coroutineContext
和CoroutineScope
所做的事情看起来非常混乱。您应该遵循通常的指导原则。我只是尝试使用Main,但没有任何区别。也没有定义特定的CoroutineScope也没有解决问题。testChannel
声明在哪里?它的范围似乎不局限于sendFunction
和receiveFunction
之间的一个交互。您还声明了一个getAllPointsChannel
,但您不使用它。它的范围局限于单个mapfunctionary
实例,但您的调用协同为每次调用反实例化此类。