I am using Retrofit2 and Rxjava2 in my android app as a networking library and NodeJS and MongoDB as a backend service.I want to fetch data from server and store data in room database in order to if user open app again it fetches data from room and not from server until some new data is added on server.
So far I have successfully fetched data from server and showing it in recycler view.
What I want to achieve:
1) Store data in room database after fetching from server.
2) Show data from room database until some new data updated on server.
This is my code below:
ApiService.java
public interface ApiService {
@POST("retrofitUsers")
@FormUrlEncoded
Observable<String> saveData(@Field("name") String name,
@Field("age") String age);
@GET("getUsers")
Observable<List<BioData>> getData();
}
RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
if(retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl("https://bookbudiapp.herokuapp.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit;
}
private RetrofitClient(){
}
}
BioData.java
public class BioData {
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
MainActivity.java
public class Users extends AppCompatActivity {
RecyclerView recycle;
UserAdapter adapter;
List<BioData> list;
CompositeDisposable compositeDisposable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycle = findViewById(R.id.recycle);
recycle.setHasFixedSize(true);
recycle.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
compositeDisposable = new CompositeDisposable();
fetchData();
}
private void fetchData(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService myApi = retrofit.create(ApiService.class);
Disposable disposable = myApi.getData().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<BioData>>() {
@Override
public void accept(List<BioData> bioData) throws Exception {
adapter = new UserAdapter(bioData,getApplicationContext());
recycle.setAdapter(adapter);
}
});
compositeDisposable.add(disposable);
}
@Override
protected void onStop() {
super.onStop();
compositeDisposable.clear();
}
}
How can I add Room database in my app let me know I have no idea of it any help would be appreciated.
THANKS