简体   繁体   中英

How to use ROOM and Retrofit on Android?

I'm new in these android things and I started to learn about MVVM and how to user ROOM and Retrofit.

And here I have two questions:

  1. It's ok to use the same Repository class for retrofit requests and ROOM SQLLite DB? I'm asking that because I want to implement an app where I need to store some data locally, but also I need to have a server to process this.

  2. Here I have a question about ROOM with LiveData... more exactly, I need a little advice about how can I implement a get or a query... I started using LiveData, but I had success only implemented a getAll function... like getAllUsers and for simple function where I need only a specific user, like getUserById, I implemented in the usual way, using AsyncTask, so without LiveData. My question is... It's good to make queries without LiveData? If the answer is yes I do not need any more explications, but if the answer is NO can anyone give me some advice on how can I do that?

1) For the first question, I believe we should follow the best practice for your problem of the repository. simply, It's Ok to do so, but you should implement that in the best practice as I said. Following Single Source of Truth Principle , you could use your room database as your only source of data, and once you get the data from the database you can request the data from the server and append these data to your local database. Because maybe a network failure occurs, so the cache here works fine and gives a better user experience. Check the hyperlink mentioned before for the official documentation, and check this video as well.

2) For me, I'm using RXJava2 with Room database. I believe it works fine, I'll share with you these 2 articles which discussed how to apply RXJava2 with Room Article 1 Article 2

But also you can use LiveData in your queries.

Note : I don't recommend using Async Task, because according to official documentation it's no deprecated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM