Skip to content

Instantly share code, notes, and snippets.

@quentin7b
Last active June 6, 2019 17:32
Show Gist options
  • Save quentin7b/e0cba1ba4c44e57157b5df06ec2bc487 to your computer and use it in GitHub Desktop.
Save quentin7b/e0cba1ba4c44e57157b5df06ec2bc487 to your computer and use it in GitHub Desktop.
Android ViewModel use LiveData as an Event bus
class TheActivity : AppCompatActivity() {
private val theSharedViewModel by viewModel<TheSharedViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
// bla bla bla
theSharedViewModel.getEvent().observe(this, Observer {
Log.i("TheSharedEvent", "Event Triggered")
})
}
}
class CrewListFragment : Fragment() {
// Note that the viewModel is by `sharedViewModel`, which is just a way of sharing it
// See https://developer.android.com/topic/libraries/architecture/viewmodel#sharing
private val theSharedViewModel: TheSharedViewModel by sharedViewModel()
// This is called by something
private fun someActionThatShouldTriggerTheEvent() = theSharedViewModel.triggerEvent()
}
class TheSharedViewModel() : ViewModel() {
// The event itself is a MutableLiveData of Unit (kotlin useless object which is very useful in fact)
private var theEvent: MutableLiveData<Unit> = MutableLiveData()
// Kind of a getter but casted as LiveData to prevent updates from outsite viewmodel
fun getEvent(): LiveData<State> = crewState
// Trigger the event update
fun triggerEvent() {
theEvent.postValue(Unit)
}
}
@quentin7b
Copy link
Author

Note that I used koin as dif

@MoeHamoud
Copy link

Cool, was looking for something like this - thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment