Issue
In my Android app I would like to use RxJava2 instead of AsyncTasks to query my local SQLite DB. I don't want to use Room
or SqlBrite
wrappers. So is it possible to get for example an Observable<List<Invoice>>
from such a query? If yes please provide an example.
e.g. I want to put the following method inside Observable-Observer pattern so it returns an Observable<List<Invoice>>
private List<Invoice> fetchInvoices() {
Cursor cursor = null;
try {
cursor = getContentResolver().query(JPBContentProvider.CONTENT_URI,
null, null, null, null);
if (cursor != null) {
List<Invoice> list = new ArrayList<>();
while (cursor.moveToNext()) {
list.add(Invoice.from(cursor));
}
return list;
}
} catch (Exception ex) {
return null;
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
Solution
There are many ways to achieve what you want. You have not provided much context, so I will assume the following as an example:
- you have some
Invoice
s stored in the database - you have some method that fetches those from DB and returns the results as
List
The example is for Kotlin, would be pretty similar in Java though.
So here is your DB fetch method:
fun queryInvoices(): List<Invoice>{
val results = arrayListOf<Invoice>()
// your logic to retrieve data from SQLite
return results
}
Assuming you need to fetch different types of data, it makes sense to define a generic method which will do the Rx magic. This is basically a 1-liner in Kotlin:
fun <T>rxFetchData(func: () -> List<T>): Single<List<T>> = Single.fromCallable(func)
How it works: the argument of this method is a function that takes no arguments (in this example) and returns a List
of some type. Single.fromCallable defers the execution of this function until you subscribe (check the link for more info).
Usage:
fun fetchInvoices() {
rxFetchData(::queryInvoices)
.subscribeOn(io())
.observeOn(mainThread())
.subscribe(
{ data ->
Log.i("onSuccess", " fetched ${data.size} invoices")
},
{ error ->
error.printStackTrace()
})
}
And here are the imports you will need:
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.schedulers.Schedulers.io
UPDATE
You could do something like that (Java):
public Single<List<Invoice>> invoices(){
return Single.fromCallable(this::fetchInvoices);
}
Answered By - Droidman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.