Reputation: 1396
lets say i have observable that call rest api service then store the result in database:
public Observable<Boolean> initDB() {
return this.restApi.feedsEntityList()
.flatMap(feedEntityList -> this.mNewsCache.saveFeeds(feedEntityList));
}
the save Observable perform the database saving and should return true in case of success or false in case of an error occurred:
public Observable<Boolean> saveFeeds(List<FeedEntity> feedEntity) {
if (feedEntity != null) {
return Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
try {
Log.d("DB: ", "saving Feed to DB");
for (FeedEntity feeds : feedEntity) {
feeds.save();
}
subscriber.onNext(true);
subscriber.onCompleted();
} catch (Exception exception) {
subscriber.onError(exception);
}
}
});
} else return Observable.empty();
}
in this last observable, i am not sure if i am doing it correctly. i.e. return true if database saving operation is done successfully. return false otherwise!
also, should i return feedEntity is null?
is that correct? and how should i check if observable returns true, false or empty Observable?
Upvotes: 2
Views: 22360
Reputation: 67259
and how should i check if observable returns true, false [...]
When you subscribe to an Observable<Boolean>
that emits either true or false, onNext(Boolean)
will be called with a value of either true or false.
For example:
saveFeed(feeds).subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean result) {
// result will be either true or false.
}
});
how should i check if observable returns [...] empty Observable
As per the documentation, Observable.empty()
emits nothing, then completes. Your onNext()
will never be called, but onComplete()
will be called.
If you really wanted to, you could monitor whether onNext()
is called, and if you onNext()
isn't called but onComplete()
is, you know it never emitted anything. This probably isn't really what you want though.
in this last observable, i am not sure if i am doing it correctly. i.e. return true if database saving operation is done successfully. return false otherwise!
You aren't.
You never call subscriber.onNext(false)
, so your Observable will never emit false
. An Observable<Boolean>
doesn't emit false
by default- it simply won't emit anything.
Upvotes: 5