Forked from fergusonm/gist:fb1da641246bd68275597561baa636e7
Created
September 26, 2022 08:01
-
-
Save belinwu/698379d734df65e3cd392ac401a7c3af to your computer and use it in GitHub Desktop.
Single Live Event Stream Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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