-
-
Save ismummy/e4937fd4a8cbf5868d3e9ad40ac44537 to your computer and use it in GitHub Desktop.
Room, LiveData example
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
// this file is just a pseudo code of the whole idea | |
// we have 3 entities - Booking, User and Address(Origin and Destination) | |
// example userDao | |
class UserDao { | |
public User getUser(int id); | |
} | |
// example addressDao | |
class AddressDao { | |
public Address getAddress(int id) | |
} | |
// example booking model | |
class Booking { | |
int userId = 0; // or shipperId? | |
int originId = 0; | |
int destinationId = 0; | |
User shipper; | |
Address origin; | |
Address destination; | |
} | |
// create a viewmodel | |
class ExampleViewModel extends ViewModel { | |
// create a livedata object | |
private LiveData<Booking> liveData = MutableLiveData<Booking>(); | |
// if you want to execute the database query in a background thread, declare an ExecutorService | |
// it is optional but highly recommended | |
private ExecutorService executor = Executors.newCachedThreadPool(); | |
// create a method to fetch the data | |
public void getBooking() { | |
Booking b = network.getBooking(); // perform network call or something | |
// do the whole database query | |
executor.execute(new Runnable() { | |
// grab DAOs from anywhere you've init'd them | |
// UserDao userDao = Database.getInstance().getUserDao() // or something similar | |
// AddressDao addressDao = .... | |
b.shipper = userDao.getUser(b.userId); | |
b.origin = addressDao.getAddress(b.originId); | |
b.destination = addressDao.getAddress(b.destinationId); | |
// notify livedata | |
liveData.postValue(b); | |
}); | |
} | |
// create getter for livedata | |
public LiveData<Booking> getLiveData() { | |
return liveData; | |
} | |
} | |
// in your activity file | |
class ExampleActivity extends AppCompatActivity { | |
private ExampleViewModel viewModel; | |
@override | |
public void onCreate() { | |
.... | |
.... | |
viewModel = ViewModelProviders.of(this).create(ExampleViewModel::class); | |
viewModel.getLiveData().observe(this, new Observer() { | |
public void onChanged(Booking b) { | |
// you can now use booking here | |
final Booking fetchedBooking = b; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment