Skip to content

Instantly share code, notes, and snippets.

@adigunhammedolalekan
Created February 17, 2019 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adigunhammedolalekan/5b04cd90ff8ba76a5f13484444a175f9 to your computer and use it in GitHub Desktop.
Save adigunhammedolalekan/5b04cd90ff8ba76a5f13484444a175f9 to your computer and use it in GitHub Desktop.
Room, LiveData example
// 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;
}
});
}
}
@ismummy
Copy link

ismummy commented May 11, 2019

Nice...I just understand this concept better now....lol

@ismummy
Copy link

ismummy commented May 11, 2019

Basically, the issue with the approach I was using and this is....all the Dao sends data with livedata and cannot be called in the executor....so I resolved to using converter in booking class, which works for ma need.

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