I\'m looking into converting my android app to use Rxjava for network requests. I currently access a webservice similar to:
getUsersByKeyword(String query, int l
I've done this and it's actually not that hard.
The approach is to model every first request (offset 0) in a firstRequestsObservable. To make it easy, you can make this as a PublishSubject where you call onNext()
to feed in the next request, but there are smarter non-Subject ways of doing it (e.g., if requests are done when a button is clicked, then the requestObservable is the clickObservable mapped through some operators).
Once you have firstRequestsObservable
in place, you can make responseObservable
by flatMapping from firstRequestsObservable
and so forth, to make the service call.
Now here comes the trick: make another observable called subsequentRequestsObservable
which is mapped from responseObservable
, incrementing the offset (for this purpose it's good to include, in the response data, the offset of the originating request). Once you introduce this observable, you now have to change the definition of responseObservable
so that it depends also on subsequentRequestsObservable
. You then get a circular dependency like this:
firstRequestsObservable -> responseObservable -> subsequentRequestsObservable -> responseObservable -> subsequentRequestsObservable -> ...
To break this cycle, you probably want to include a filter
operator in the definition of subsequentRequestsObservable
, filtering out those cases where the offset would pass the "total" limit. The circular dependency also means that you need to have one of those being a Subject, otherwise it would be impossible to declare the observables. I recommend responseObservable
to be that Subject.
So, all in all, you first initialize responseObservable as a Subject, then declare firstRequestsObservable, then declare subsequentRequestsObservable as the result of passing responseObservable through some operators. responseObservable can then be "fed in" by using onNext
.