Running with retrofit
This is my interface:
#GET("solicitation/all")
Observable<SolicitationResponse> getAll(#Query("X-Authorization") String apiKey);
This is where I run it:
apiService.getAll(getResources().getString(R.string.api_key))
.subscribeOn(Schedulers.io())
.flatMapIterable(SolicitationResponse::getData)
.observeOn(AndroidSchedulers.mainThread())
.delay(5L, java.util.concurrent.TimeUnit.SECONDS) // THIS DOESN'T WORK LIKE I WANT IT TO..
.repeat()
.subscribe(s -> Log.e(TAG, "data: " + s.getName()));
So, two questions:
1) How can I add a conditional to only run if we have internet connection?
This doesn't work:
if (NetworkUtils.isConnected()) {
//observable above here
}
Why? Because the conditional code doesn't run itself endlessly, which means it will only check if we have internet connection once, ergo, it will crash if we lose it.
Is there any way to add a conditional before running the getAll method?
2) I need to add an interval before or after the task, by inserting .delay it will delay the subscription, which is not what I want or need. How can I accomplish it in this particular situation?
here's a suggestion:
Observable.fromCallable(() -> NetworkUtils.isConnected())
.flatMap(isConnected -> {
if (isConnected) {
return apiService.getAll(getResources().getString(R.string.api_key))
.subscribeOn(Schedulers.io())
.flatMapIterable(SolicitationResponse::getData);
} else {
return Observable.empty();
}
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.immediate())
.repeatWhen(observable -> observable.delay(5, TimeUnit.SECONDS))
.subscribe(s -> Log.e(TAG, "data: " + s.getName()));
1) the most straightforward way is to add the network check to the stream and using flatMap() conditionally decide what to do further.
2) adding delay before can be done using delaySubscription() with the desired value, but then the delay will happen also with the first time, so the second approach of adding delay at the end seems more appropriate here, and can be done using repeatWhen()
Related
Currently I have a service that returns that returns a list of parameters. if there are 4 parameters I need to perform one request per parameter to the same endpoint using the each of the parameter. After that I need to save the list of results of all the request into a collection. If I don't know how many request do I have to perform, What rxJava operator I need to use and how should I use it?? .
Take into account that I don't need to wait for the answer of the first request to perform the second one and ....
I have seen that the zip operator allow me to perform parallel request but I have to know the number of request to use it.
You can use flatMap to create Observable for each parameter and execute them in parallel as in
Observable.fromArray(parameters)
.flatMap(val -> Observable.just(val)
.subscribeOn(Schedulers.io())
.map(request -> doApiCall(request))
)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response -> log(response));
At the end I implemented it this way:
public Subscription getElementsByStage(List <String> requiredStages) {
List < Observable <ElementsResponse>> observables = new ArrayList < > ();
for (String stage: requiredStages) {
ElementsRequest request = buildElementRequest(stage);
observables.add(request).subscribeOn(Schedulers.newThread()));
}
Observable zippedObservables = Observable.zip(observables, this::arrangeElementsByStage);
return zippedObservables
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber <HashMap<Stage,Element>>() {
.....
}
}
I want to implement place autocomplete in Android application, and for this I'm using Retrofit and RxJava. I want to make response every 2 seconds after user type something. I'm trying to use debounce operator for this, but it's not working. It's giving me the result immediately without any pause.
mAutocompleteSearchApi.get(input, "(cities)", API_KEY)
.debounce(2, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(prediction -> Observable.fromIterable(prediction.getPredictions()))
.subscribe(prediction -> {
Log.e(TAG, "rxAutocomplete : " + prediction.getStructuredFormatting().getMainText());
});
As #BenP says in the comment, you appear to be applying debounce to the Place Autocomplete service. This call will return an Observable that emits a single result (or error) before completing, at which point the debounce operator will emit that one and only item.
What you probably want to be doing is debouncing the user input with something like:
// Subject holding the most recent user input
BehaviorSubject<String> userInputSubject = BehaviorSubject.create();
// Handler that is notified when the user changes input
public void onTextChanged(String text) {
userInputSubject.onNext(text);
}
// Subscription to monitor changes to user input, calling API at most every
// two seconds. (Remember to unsubscribe this subscription!)
userInputSubject
.debounce(2, TimeUnit.SECONDS)
.flatMap(input -> mAutocompleteSearchApi.get(input, "(cities)", API_KEY))
.flatMap(prediction -> Observable.fromIterable(prediction.getPredictions()))
.subscribe(prediction -> {
Log.e(TAG, "rxAutocomplete : " + prediction.getStructuredFormatting().getMainText());
});
I am using Retrofit 2 along with RxJava 2 adapters.
Whenever the server returns 401 Unauthorized, I refresh the token and retry the request:
apiCall.retryWhen(es -> es
.flatMap(e -> {
if (isUnauthorizedException(e)) {
return refreshToken();
}
return Flowable.<User>error(e);
}));
Where refreshToken is a simple retrofit call:
public Flowable<User> refreshToken() {
return retrofitService.login(userCredentials);
}
Now, I would like to limit the number of times such refresh is possible. However, simply adding take(1) does not work, because then retryWhen receives onCompleted immediately after onNext and cancels the request before retrying it.
Naturally I could do take(2) to achieve the desired effect but it seems like a hack.
What is the most elegant way to achieve it using Rx operators? Also is there an operator with "assertion" logic (to get rid of if in the flat map)?
Also I am aware I can achieve the same thing using OkHttp interceptors, but I am interested in Retrofit-RxJava solution.
There is a nice example from documentation
this retries 3 times, each time incrementing the number of seconds it waits.
ObservableSource.create((Observer<? super String> s) -> {
System.out.println("subscribing");
s.onError(new RuntimeException("always fails"));
}).retryWhen(attempts -> {
return attempts.zipWith(ObservableSource.range(1, 3),
(n, i) -> i).flatMap(i -> {
System.out.println("delay retry by " + i + " second(s)");
return ObservableSource.timer(i, TimeUnit.SECONDS);
});
}).blockingForEach(System.out::println);
Output is:
subscribing
delay retry by 1 second(s)
subscribing delay retry by 2 second(s)
subscribing delay retry by 3 second(s)
subscribing
you could modify this example according to your requirements.
I'm building a 2 Player game on Android. The game works turnwise, so player 1 waits until player 2 made his input and vice versa. I have a webserver where I run an API with the Slim Framework. On the clients I use Retrofit. So on the clients I would like to poll my webserver (I know it's not the best approach) every X seconds to check whether there was an input from player 2 or not, if yes change UI (the gameboard).
Dealing with Retrofit I came across RxJava. My problem is to figure out whether I need to use RxJava or not? If yes, are there any really simple examples for polling with retrofit? (Since I send only a couple of key/value pairs) And if not how to do it with retrofit instead?
I found this thread here but it didn't help me too because I still don't know if I need Retrofit + RxJava at all, are there maybe easier ways?
Let's say the interface you defined for Retrofit contains a method like this:
public Observable<GameState> loadGameState(#Query("id") String gameId);
Retrofit methods can be defined in one of three ways:
1.) a simple synchronous one:
public GameState loadGameState(#Query("id") String gameId);
2.) one that take a Callback for asynchronous handling:
public void loadGameState(#Query("id") String gameId, Callback<GameState> callback);
3.) and the one that returns an rxjava Observable, see above. I think if you are going to use Retrofit in conjunction with rxjava it makes the most sense to use this version.
That way you could just use the Observable for a single request directly like this:
mApiService.loadGameState(mGameId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GameState>() {
#Override
public void onNext(GameState gameState) {
// use the current game state here
}
// onError and onCompleted are also here
});
If you want to repeatedly poll the server using you can provide the "pulse" using versions of timer() or interval():
Observable.timer(0, 2000, TimeUnit.MILLISECONDS)
.flatMap(mApiService.loadGameState(mGameId))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GameState>() {
#Override
public void onNext(GameState gameState) {
// use the current game state here
}
// onError and onCompleted are also here
}).
It is important to note that I am using flatMap here instead of map - that's because the return value of loadGameState(mGameId) is itself an Observable.
But the version you are using in your update should work too:
Observable.interval(2, TimeUnit.SECONDS, Schedulers.io())
.map(tick -> Api.ReceiveGameTurn())
.doOnError(err -> Log.e("Polling", "Error retrieving messages" + err))
.retry()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(sub);
That is, if ReceiveGameTurn() is defined synchronously like my 1.) above, you would use map instead of flatMap.
In both cases the onNext of your Subscriber would be called every two seconds with the latest game state from the server. You can process them one after another of limit the emission to a single item by inserting take(1) before subscribe().
However, regarding the first version: A single network error would be first delivered to onError and then the Observable would stop emitting any more items, rendering your Subscriber useless and without input (remember, onError can only be called once). To work around this you could use any of the onError* methods of rxjava to "redirect" the failure to onNext.
For example:
Observable.timer(0, 2000, TimeUnit.MILLISECONDS)
.flatMap(new Func1<Long, Observable<GameState>>(){
#Override
public Observable<GameState> call(Long tick) {
return mApiService.loadGameState(mGameId)
.doOnError(err -> Log.e("Polling", "Error retrieving messages" + err))
.onErrorResumeNext(new Func1<Throwable, Observable<GameState>(){
#Override
public Observable<GameState> call(Throwable throwable) {
return Observable.emtpy());
}
});
}
})
.filter(/* check if it is a valid new game state */)
.take(1)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GameState>() {
#Override
public void onNext(GameState gameState) {
// use the current game state here
}
// onError and onCompleted are also here
}).
This will every two seconds:
* use Retrofit to get the current game state from the server
* filter out invalid ones
* take the first valid one
* and the unsubscribe
In case of an error:
* it will print an error message in doOnNext
* and otherwise ignore the error: onErrorResumeNext will "consume" the onError-Event (i.e. your Subscriber's onError will not be called) and replaces it with nothing (Observable.empty()).
And, regarding the second version: In case of a network error retry would resubscribe to the interval immediately - and since interval emits the first Integer immediately upon subscription the next request would be sent immediately, too - and not after 3 seconds as you probably want...
Final note: Also, if your game state is quite large, you could also first just poll the server to ask whether a new state is available and only in case of a positive answer reload the new game state.
If you need more elaborate examples, please ask.
UPDATE: I've rewritten parts of this post and added more information in between.
UPDATE 2: I've added a full example of error handling with onErrorResumeNext.
Thank you, I finally made it in a similar way based the post I referred to in my question. Here's my code for now:
Subscriber sub = new Subscriber<Long>() {
#Override
public void onNext(Long _EmittedNumber)
{
GameTurn Turn = Api.ReceiveGameTurn(mGameInfo.GetGameID(), mGameInfo.GetPlayerOneID());
Log.d("Polling", "onNext: GameID - " + Turn.GetGameID());
}
#Override
public void onCompleted() {
Log.d("Polling", "Completed!");
}
#Override
public void onError(Throwable e) {
Log.d("Polling", "Error: " + e);
}
};
Observable.interval(3, TimeUnit.SECONDS, Schedulers.io())
// .map(tick -> Api.ReceiveGameTurn())
// .doOnError(err -> Log.e("Polling", "Error retrieving messages" + err))
.retry()
.subscribe(sub);
The problem now is that I need to terminate emitting when I get a positive answer (a GameTurn). I read about the takeUntil method where I would need to pass another Observable which would emit something once which would trigger the termination of my polling. But I'm not sure how to implement this.
According to your solution, your API method returns an Observable like it is shown on the Retrofit website. Maybe this is the solution? So how would it work?
UPDATE:
I considered #david.miholas advices and tried his suggestion with retry and filter. Below you can find the code for the game initialization. The polling should work identically: Player1 starts a new game -> polls for opponent, Player2 joins the game -> server sends to Player1 opponent's ID -> polling terminated.
Subscriber sub = new Subscriber<String>() {
#Override
public void onNext(String _SearchOpponentResult) {}
#Override
public void onCompleted() {
Log.d("Polling", "Completed!");
}
#Override
public void onError(Throwable e) {
Log.d("Polling", "Error: " + e);
}
};
Observable.interval(3, TimeUnit.SECONDS, Schedulers.io())
.map(tick -> mApiService.SearchForOpponent(mGameInfo.GetGameID()))
.doOnError(err -> Log.e("Polling", "Error retrieving messages: " + err))
.retry()
.filter(new Func1<String, Boolean>()
{
#Override
public Boolean call(String _SearchOpponentResult)
{
Boolean OpponentExists;
if (_SearchOpponentResult != "0")
{
Log.e("Polling", "Filter " + _SearchOpponentResult);
OpponentExists = true;
}
else
{
OpponentExists = false;
}
return OpponentExists;
}
})
.take(1)
.subscribe(sub);
The emission is correct, however I get this log message on every emit:
E/Pollingļ¹ Error retrieving messages: java.lang.NullPointerException
Apperently doOnError is triggered on every emit. Normally I would get some Retrofit debug logs on every emit which means that mApiService.SearchForOpponent won't get called. What do I do wrong?
I'm playing around with RXJava, retrofit in Android. I'm trying to accomplish the following:
I need to poll periodically a call that give me a Observable> (From here I could did it)
Once I get this list I want to iterate in each Delivery and call another methods that will give me the ETA (so just more info) I want to attach this new info into the delivery and give back the full list with the extra information attached to each item.
I know how to do that without rxjava once I get the list, but I would like to practice.
This is my code so far:
pollDeliveries = Observable.interval(POLLING_INTERVAL, TimeUnit.SECONDS, Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR))
.map(tick -> RestClient.getInstance().getApiService().getDeliveries())
.doOnError(err -> Log.e("MPB", "Error retrieving messages" + err))
.retry()
.subscribe(deliveries -> {
MainApp.getEventBus().postSticky(deliveries);
});
This is giving me a list of deliveries. Now I would like to accomplish the second part.
Hope I been enough clear.
Thanks
Finally I found a nice way to do it.
private void startPolling() {
pollDeliveries = Observable.interval(POLLING_INTERVAL, TimeUnit.SECONDS, Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR))
.flatMap(tick -> getDeliveriesObs())
.doOnError(err -> Log.e("MPB", "Error retrieving messages" + err))
.retry()
.subscribe(this::parseDeliveries, Throwable::printStackTrace);
}
private Observable<List<Delivery>> getDeliveriesObs() {
return RestClient.getInstance().getApiService().getDeliveries()
.flatMap(Observable::from)
.flatMap(this::getETAForDelivery)
.toSortedList((d1, d2) -> {
if (d1.getEta() == null) {
return -1;
}
if (d2.getEta() == null) {
return 1;
}
return d1.getEta().getDuration().getValue() > d2.getEta().getDuration().getValue() ? 1 : -1;
});
}
Let's go step by step.
First we create an Observable that triggers every POLLING_INTERVAL time the method getDeliveriesObs() that will return the final list
We use retrofit to get an Observable of the call
We use flatMap to flattern the resut list and get in the next flatmap a Delivery item, one by one.
Then we get the estimated time of arrival set inside the Delivery object and return it
We sort the list to order by estimated time of arrival.
In case of error we print and retry so the interval does not stop
We subscribe finally to get the list sorted and with ETA inside, then we just return it or whatever you need to do with it.
It's working properly and it's quite nice, I'm starting to like rxjava :)
I haven't spent a lot of time with Java 8 lambdas, but here's an example of mapping each object to a different object, then getting a List<...> out at the other end in plain ol' Java 7:
List<Delivery> deliveries = ...;
Observable.from(deliveries).flatMap(new Func1<Delivery, Observable<ETA>>() {
#Override
public Observable<ETA> call(Delivery delivery) {
// Convert delivery to ETA...
return someEta;
}
})
.toList().subscribe(new Action1<List<ETA>>() {
#Override
public void call(List<ETA> etas) {
}
});
Of course, it'd be nice to take the Retrofit response (presumably an Observable<List<Delivery>>?) and just observe each of those. For that we ideally use something like flatten(), which doesn't appear to be coming to RxJava anytime soon.
To do that, you can instead do something like this (much nicer with lambdas). You'd replace Observable.from(deliveries) in the above example with the following:
apiService.getDeliveries().flatMap(new Func1<List<Delivery>, Observable<Delivery>>() {
#Override
public Observable<Delivery> call(List<Delivery> deliveries) {
return Observable.from(deliveries);
}
}).flatMap(...)