Skip to content

Instantly share code, notes, and snippets.

@Sethathi
Created March 23, 2022 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sethathi/11da9c19b6c5cdceacd5d000c544296e to your computer and use it in GitHub Desktop.
Save Sethathi/11da9c19b6c5cdceacd5d000c544296e to your computer and use it in GitHub Desktop.
// `BookingsActivity` is rotatable and currently loads bookings from API on each rotation. How can we prevent this from happening?
class BookingViewModel(
private val repository: BookingsRepository
) : ViewModel() {
// We want to make sure that this is only settable privately.
val bookings = MutableLiveData<List<Booking>>()
fun loadBookings() {
val bookings = repository.getBookings()
bookings.postValue(bookings)
}
}
class BookingsActivity : AppCompatActivity() {
lateinit var bookingViewModelFactory: BookingViewModelFactory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel = ViewModelProviders.of(this, bookingViewModelFactory).get(BookingViewModel::class.java)
viewModel.bookings.observe(this, Observer {
// Update UI with list of bookings
})
viewModel.loadBookings()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment