문제

Right now I am exploring some options for an android learning project. I am trying to communicate with my rails api (also a learning project).

After doing some research, I think I have settled on a scheme that uses retrofit and otto.

What I end up with is this. When I want to make a call to my rails server (in this case to do a signup) I do this in the activity.

 mBus.post(new SignupRequestEvent(new UserRequestParams(mName,mEmail,mPassword,mPasswordConfirmation )));

and then in the same activity I have this.

@Subscribe
public void onSignupCompleted(SignupCompletedEvent event) {
    System.out.println(String.format("in onSignupCompleted, got token = %s ", event.getParams().getToken()));

}

The problem here is that, as it stands, every api request type and it corresponding response type would be a unique event type and require it's own class, which seems like a lot of boiler plate type of code.

For example to handle sign in and sign out I would need these two classes:

public class SignupRequestEvent {
    protected UserRequestParams mSignupParams;

    public SignupRequestEvent(UserRequestParams signupParams) {
        mSignupParams = signupParams;
    }

    public UserRequestParams getParams() {
        return mSignupParams;
    }

}

public class SignupCompletedEvent {

    private SignupCompletedParams mSignupCompletedParams;
    public SignupCompletedParams getParams() {
        return mSignupCompletedParams;
    }
    public SignupCompletedEvent(SignupCompletedParams signupCompletedParams) {
        mSignupCompletedParams = signupCompletedParams;
    }

}

And I think most of the event classes would be pretty much identical.

I am thinking I should just have 2 events for api calls , one for requests and one for responses, but then each method that receives an api response event would need to check if it is a response to the desired request.

This option would mean something like this:

ApiRequestEvent apiRequestEvent = new ApiRequestEvent();
apiRequestEvent.setAction("SIGNUP");
apiRequestEvent.setParameters(new UserRequestParams(mName,mEmail,mPassword,mPasswordConfirmation ));
mBus.post(apiRequestEvent);

and then to handle the response something like this:

@Subscribe
public void onSignupCompleted(ApiResponseAvailable event) {
    if (event.getResponseTo != "SIGNUP") return;
    System.out.println(String.format("in onSignupCompleted, got token = %s ", event.getParams().getToken()));

Maybe there is a way to use generics?

Can someone explain how to effectively use an event bus when there are a set of events that can be grouped together like this?

도움이 되었습니까?

해결책

You're overthinking it - just go ahead and create a message object for each event.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top