假设我有一个发出流的类,以及另一个类中收集流的函数:
这有效
class DebugMessage { val sharedFlow = MutableSharedFlow<String>() fun makeFlow() { GlobalScope.launch(Dispatchers.Default) { for (i in 0 until 10) { sharedFlow.emit(Random.nextInt(1,100).toString()) delay(200) } } } fun getFlow(): Flow<String> { makeFlow() return sharedFlow } }
和
private fun collectDebugMsg() { GlobalScope.launch(Dispatchers.Default) { val getFlow = DebugMessage().getFlow() getFlow.collect { Timber.d("VALUE IS $it") } } }
这按预期工作,但有点无用。我需要拆分makeFlow
和getFlow
功能。我会先调用该makeFlow
函数,然后再getFlow
调用该函数,例如:
这不起作用
class DebugMessage { val sharedFlow = MutableSharedFlow<String>() fun makeFlow() { GlobalScope.launch(Dispatchers.Default) { for (i in 0 until 10) { sharedFlow.emit(Random.nextInt(1,100).toString()) delay(200) } } } fun getFlow(): Flow<String> { //makeFlow() // Call 'makeFlow' from outside the DebugMessage Class return sharedFlow } }
和
private fun collectDebugMsg() { GlobalScope.launch(Dispatchers.Default) { DebugMessage().makeFlow() // Call 'makeFlow' from outside the DebugMessage Class val getFlow = DebugMessage().getFlow() getFlow.collect { Timber.d("VALUE IS $it") } } }
该流不再收集任何东西。有人知道这是为什么吗?