On my Android project I'm heavily relying on RxJava2, SqlBrite(with RxJavaInterop) and SqlDelight.
I got one rx stream that is supposed to go indefinitely (until my service stops) and on it I have a .flatMap of Function<String, ObservableSource<Action>>.
Meaning, this flatMap contains a Subject<Action>, will receive String actionId, do some (irrelevant for the question) processing on those actionId, and depending on condition should query the database for the Action object and dispatch it to the subject
My first approach was to do the query directly:
Cursor c = db.query(...);
if(c.moveFirst()) {
Action a = Action.SELECT_ALL_MAPPER.map(c);
subject.onNext(selectAll);
}
But this blocks the running thread and I rather trigger this on its own stream that should do the following:
- query (should return 0 or 1 item)
- if there's a value: map to
Actionobject and push the value to thesubject - if there's no value: terminate/dispose.
- the
subjectcannot receive terminate or error. It must stay alive for future events.
My current approach is the following code:
RxJavaInterop.toV2Observable(db.createQuery(
Action.TABLE_NAME,
Action.FACTORY.Select_by_id(actionId).statement)
.mapToOne(new Func1<Cursor, Action>() {
@Override public Action call(Cursor cursor) {
return Action.SELECT_ALL_MAPPER.map(cursor);
}
}))
.take(1)
.subscribe(new Consumer<Action>() {
@Override public void accept(Action action) throws Exception {
subject.onNext(action);
}
});
And although this seems to do the trick on the first impression, I see a few errors on it:
- I can't dispose it. Even if I get the reference to Disposable object, I cannot call it from inside
Consumer<Action>because it "might have not been initialised" (which I understand the reason, it's OK). - if there's no action with the given ID, the observable will hang in there for ever, until the VM is killed.
So the question:
How can I do that?