Skip to content

Instantly share code, notes, and snippets.

@fergusonm
Last active September 26, 2022 08:01
Show Gist options
  • Save fergusonm/fb1da641246bd68275597561baa636e7 to your computer and use it in GitHub Desktop.
Save fergusonm/fb1da641246bd68275597561baa636e7 to your computer and use it in GitHub Desktop.
Single Live Event Stream Sample
class MainViewModel : ViewModel() {
sealed class Event {
object NavigateToSettings: Event()
data class ShowSnackBar(val text: String): Event()
data class ShowToast(val text: String): Event()
}
private val eventChannel = Channel<Event>(Channel.BUFFERED)
val eventsFlow = eventChannel.receiveAsFlow()
init {
viewModelScope.launch {
eventChannel.send(Event.ShowSnackBar("Sample"))
eventChannel.send(Event.ShowToast("Toast"))
}
}
fun settingsButtonClicked() {
viewModelScope.launch {
eventChannel.send(Event.NavigateToSettings)
}
}
}
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private val viewModel by viewModels<MainViewModel>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Note that I've chosen to observe in the tighter view lifecycle here.
// This will potentially recreate an observer and cancel it as the
// fragment goes from onViewCreated through to onDestroyView and possibly
// back to onViewCreated. You may wish to use the "main" lifecycle owner
// instead. If that is the case you'll need to observe in onCreate with the
// correct lifecycle.
viewModel.eventsFlow
.onEach {
when (it) {
MainViewModel.Event.NavigateToSettings -> {}
is MainViewModel.Event.ShowSnackBar -> {}
is MainViewModel.Event.ShowToast -> {}
}
}
.observeInLifecycle(viewLifecycleOwner)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment