vchernyshov
vchernyshov

Reputation: 39

How to make decision RxJava?

I'm new in RxJava but want to try it with Retrofit 2 in my android project. Application supports auth and all request to server must containce token in headers, if token not valid I must send auth request.

This is my Api interface

public interface ApiRx {

    @FormUrlEncoded
    @POST("auth")
    Observable<AuthResponse> makeAuth(@FieldMap Map<String, String> fields);

    @GET("update")
    Observable<UpdateResponse> getUpdates(@Query("date") String date);
}

But I don't now how to organize if-else statements using Rx and if update request is fails with auth reason, send auth request and then retry update request.

Maybe someone has simillar case, it will be nice if you show example how to realize this case.

Upvotes: 0

Views: 122

Answers (1)

Jahnold
Jahnold

Reputation: 7683

You'll be better off changing your return types to Observable<Response<>> so it would be:

public interface ApiRx {

    @FormUrlEncoded
    @POST("auth")
    Observable<Response<AuthResponse>> makeAuth(@FieldMap Map<String, String> fields);

    @GET("update")
    Observable<Response<UpdateResponse>> getUpdates(@Query("date") String date);
}

This way you have access to the server response as well as the data. Once you've done this you can do the requests something like:

api.getUpdates(date)
    .flatMap(new Func1<Response<UpdateResponse>, Observable<UpdateResponse>>() {
        @Override
        public Observable<UpdateResponse> call(Response<UpdateResponse> response) {

            if (!response.isSuccess() && response.code() == 403) {
                // return makeAuth(fields)
                // .flatMap(save auth)
                // .flatMap(return getUpdates)
                // .flatMap(return Observable.just(response.body())
            }
            else {
                return Observable.just(response.body());
            }

        }
    })
    .subscribe();

I've had to be a bit vague in the if auth failed section as I don't know how your system is setup but it should give you the right idea.

Upvotes: 2

Related Questions