Daniel Gomez Rico
Daniel Gomez Rico

Reputation: 15955

Multiple use of same Observable with Retrofit

I have a manager that encapsulates the call to the retrofit service because I need to save the session token and object on login, then:

class LoginManager {

     public static Observable<Session> login(String email, String password) {
        Credential credential = new Credential(email, password);
        Observable<Session> observable = SERVICE.createSession(credential);

        observable.subscribe(new Subscriber<Session>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(Session session) {
                String token = session.getToken();
                saveToken(token);
                save(session.buildCustomer());
            }
        });

        return observable;
    } 
}

My Service looks like:

public interface CustomerService {

    @POST("/api/sessions/customer")
    Observable<Session> createSession(@Body Credential credential);

}

Is it correct to use the observable inside the manager and outside in my activity?

What problems can it have?

---- EDIT

Changed to map:

class LoginManager {

     public static Observable<Session> login(String email, String password) {
        Credential credential = new Credential(email, password);
        return SERVICE.createSession(credential)
        .map(session - {
            String token = session.getToken();
            saveToken(token);
            save(session.buildCustomer());
            return session;
        });
    } 

}

It is a good idea?

Upvotes: 0

Views: 255

Answers (1)

maclir
maclir

Reputation: 3309

The observable will start emitting whenever someone subscribes to it.

What I would suggest you to do in your manager would be to return the observable and just add .doOnNext() to it.

return observable.doOnNext(new Action1<Session>() {
    @Override
    public void call(final Session session) {
        String token = session.getToken();
        saveToken(token);
        save(session.buildCustomer());
    }   
});

.map is used when you want to change the observable type while doing an operation on it.

This way, whenever onNext would happen on your observable (i.e subscribe from your activity), you would have access to the Session there.

Upvotes: 2

Related Questions