片段未接收从视图模型发送的通道事件



当我单击DialogFragment内的按钮时,我正试图在MainFragment中显示Snackbar
当我从对话框类调用发送事件函数(在ViewModel中(时,不会发生任何事情。我不知道我做错了什么,但在MainFragment中做类似事情的其他函数工作得很好。

在ViewModel中,清除MainFragment中的editText的clearInput()函数可以工作,但onEditNoteClicked()不工作,当我调用它时也不会发生任何事情。

NoteOptionsDialog类别:

@AndroidEntryPoint
class NoteOptionsDialog : BottomSheetDialogFragment() {
private val viewModel: NotesViewModel by viewModels()
private fun setupClickListeners(view: View) {
view.bottom_options_edit.setOnClickListener {
viewModel.onEditNoteClicked()
dismiss()
}
}  

NotesViewModel类:

@HiltViewModel
class NotesViewModel @Inject constructor(
private val noteDao: NoteDao,
private val preferencesManager: PreferencesManager,
private val state: SavedStateHandle
) : ViewModel() {
private val notesEventChannel = Channel<NotesEvent>()
val notesEvent = notesEventChannel.receiveAsFlow()
fun onSaveNoteClick() {
val newNote = Note(noteText = noteText, noteLabelId = labelId.value)
createNote(newNote)
}
private fun createNote(newNote: Note) = viewModelScope.launch {
noteDao.insertNote(newNote)
clearInput()
}
private fun clearInput() = viewModelScope.launch {
notesEventChannel.send(NotesEvent.ClearEditText)
}
fun onEditNoteClicked() = viewModelScope.launch {
notesEventChannel.send(NotesEvent.ShowToast)
}
fun onNoteSelected(note: Note, view: View) = viewModelScope.launch {
notesEventChannel.send(NotesEvent.ShowBottomSheetDialog(note, view))
}
sealed class NotesEvent {
object ClearEditText : NotesEvent()
object ShowToast : NotesEvent()  
data class ShowBottomSheetDialog(val note: Note, val view: View) : NotesEvent()
}  

注释碎片类别:

@AndroidEntryPoint
class NotesFragment : Fragment(R.layout.fragment_home), NotesAdapter.OnNoteItemClickListener,
LabelsAdapter.OnLabelItemClickListener {
private val viewModel: NotesViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?){
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.notesEvent.collect { event ->
when (event) {
is NotesViewModel.NotesEvent.ShowBottomSheetDialog -> {
NoteOptionsDialog().show(childFragmentManager, null)
}
is NotesViewModel.NotesEvent.ClearEditText -> {
et_home_note.text.clear()
}
is NotesViewModel.NotesEvent.ShowToast -> {
Snackbar.make(requireView(), "Snack!", Snackbar.LENGTH_LONG).show()
}
}

找到了解决方案。对于碎片,我应该使用by activityViewModels()而不是by viewModels()

private val viewModel: NotesViewModel by activityViewModels()

在片段中初始化如下所示的视图模型,以共享同一实例

private val viewModel: NotesViewModel by activityViewModels()

最新更新