frankelot
frankelot

Reputation: 14459

Retrofit observable works only once

I understand that, by default, observables created by retrofit are "cold" observables.

I have this specific call to my server endpoint

@POST("oauth/token")
Observable<Token> signIn(@Field("username") String username, @Field("password") String password);

When I do:

public class LoginUseCase extends Subscriber<Profile> {
    public void logIn(String username, String password) {
        Subscription subscription = myApi.signIn(username, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
        this.add(subscription);
    }
}

I receive the onNext onError onComplete callbacks, as you would expect.

The problem arises when the login fails and I try again. Calling the login() method a second time doesn't trigger the http call, and I don't get any callbacks.

By the way, Im doing this on my onComplete() method

@Override
public void onCompleted() {
    this.unsubscribe();
}

Is there a way to tell retrofit/rxandroid to re make the http call everytime I call myApi.signin(). Am I even approaching this the right way?

Notes: - Im using dagger2 in my project and the myApi object is a singleton. - I'm able to reproduce the error even when I use different username/pass configs between the first and second try

Upvotes: 4

Views: 1007

Answers (1)

Kiskae
Kiskae

Reputation: 25603

Once Subscriber#unsubscribe() is called that subscriber can never receive new values. You will need to recreate your subscriber each time you want to subscribe to a new observable.

What is happening is that in the call to Subscriber#add(Subscription) it sees that the subscriber has already been unsubscribed and immediately cancels the new subscription.

Upvotes: 4

Related Questions