android Kotlin通道不收集值

wko9yo5t  于 2022-11-03  发布在  Android
关注(0)|答案(1)|浏览(138)

我尝试从ViewModel发送一个变量值到可组合屏幕。我尝试使用调试器来找出它在哪里卡住了。它似乎发送了值,但实际上从未接收到它。
这是我正在使用的代码:

新事件.kt

@Composable
fun NewEvent(
    viewModel: NewEventViewModel = viewModel(), 
    navController: NavController
){
    val context = LocalContext.current

    LaunchedEffect(context){
        viewModel.newEventType.collect { eventType ->
            Toast.makeText(context, eventType.toString(), Toast.LENGTH_SHORT).show()
        }
    }
}

在此处调用changeEventType()

DropdownMenu(
    expanded = menuExpanded,
    onDismissRequest = { menuExpanded = false },
) {
    eventTypeList.forEach {
        if(it != viewModel.event.eventType &&  it != EventType.UNKNOWN) {
            DropdownMenuItem(
                onClick = { viewModel.changeEventType(it); menuExpanded = false },
                text = { Text(stringResource(context.resources.getIdentifier(it.toString().lowercase(), "string", context.packageName))) }
            )
        }
    }
}

新事件视图模型.kt

private val newEventTypeChannel = Channel<EventType>()
val newEventType = newEventTypeChannel.receiveAsFlow()

fun changeEventType(newEventType: EventType){
    viewModelScope.launch {
        newEventTypeChannel.send(newEventType)
    }
}

我从GitHub下载了一个使用这个实现的示例项目,它工作了,我不知道我在这里错过了什么。

elcex8rz

elcex8rz1#

如果您想显示吐司消息,您不需要为它创建单独的可组合函数。由于Toast是动态的,不需要重新组合,因此您不需要为它创建可组合函数。
像这样实现它会更清楚、更好(在一个可组合函数中)

val context = LocalContext.current

LaunchedEffect(context){
    viewModel.newEventType.collect { eventType ->
        Toast.makeText(context, eventType.toString(), Toast.LENGTH_SHORT).show()
    }
}

DropdownMenu(
    expanded = menuExpanded,
    onDismissRequest = { menuExpanded = false },
) {
    eventTypeList.forEach {
        if(it != viewModel.event.eventType &&  it != EventType.UNKNOWN) {
            DropdownMenuItem(
                onClick = { viewModel.changeEventType(it); menuExpanded = false },
                text = { Text(stringResource(context.resources.getIdentifier(it.toString().lowercase(), "string", context.packageName))) }
            )
        }
    }
}

相关问题