繁体   English   中英

使用翻新和匕首功能,我将如何创建一个可以轻松切换端点的应用程序?

[英]Using retrofit & dagger how would I create an app where I can easily switch out end points?

目前,我的操作方式是使用ApiConfig类,如下所示:

public class ApiConfig {

public enum Build{
    RELEASE("https://api.endpoint.com"),
    STAGE("http://api.stage.endpoint.com"),
    DEV("http://api.dev.endpoint.com");


    public String endpoint;

    Build(String endpoint){
        this.endpoint = endpoint;
    }
  }
}

我有一个采用构建类型的ApiModule,因此我实例化了该组件,如下所示:

ApiComponent component = DaggerApiComponent.builder()
            .apiModule(new ApiModule(ApiConfig.Build.DEV))
            .build();

因此,现在,如果我想更改端点,则将ApiConfig.Build.DEV更改为ApiConfig.Build.STAGE或ApiConfig.Build.RELEASE。 这是正确的方法吗? 最终,我希望能够按一个按钮在这三个之间切换。

好吧,这就是我的工作:

我有一个基于互联网示例的服务工厂类。 请参阅下面的代码。

当我需要创建服务实例时,我会打电话给我。

service = ServiceFactory.createRetrofitService(GithubService.class,
            GithubService.SERVICE_ENDPOINT);

因此,如果您将3个端点添加到GithubService接口。 在所需视图的单击事件上,只需使用所需的SERVICE_ENDPOINT调用ServiceFactory。

例。

public interface GithubService {
    String RELEASE_ENDPOINT = "https://api.endpoint.com";
    String STAGE_ENDPOINT = "http://api.stage.endpoint.com";
    String DEV_ENDPOINT = "http://api.stage.endpoint.com";

    @GET("/users/{login}")
    Observable<UserResponse> getUser(@Path("login") String login);
}

在您的RELEASE按钮onClick()调用中:

private GithubService service;

service = ServiceFactory.createRetrofitService(GithubService.class,
            GithubService.SERVICE_ENDPOINT);

在您的STAGE按钮中onClick()调用:

private GithubService service;

service = ServiceFactory.createRetrofitService(GithubService.class,
            GithubService.STAGE_ENDPOINT);

在您的DEV按钮的onClick()调用中:

private GithubService service;

service = ServiceFactory.createRetrofitService(GithubService.class,
            GithubService.DEV_ENDPOINT);

服务工厂代码:

public class ServiceFactory {

    private static final String TAG = ServiceFactory.class.getSimpleName();
    /**
     * Creates a retrofit service from an arbitrary class (clazz)
     * @param clazz Java interface of the retrofit service
     * @param endPoint REST endpoint url
     * @return retrofit service with defined endpoint
     */
    public static <T> T createRetrofitService(final Class<T> clazz, final String     endPoint) {
        final RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setLog(new RestAdapter.Log() {
                    @Override
                    public void log(String message) {
                        Log.v(TAG, message);
                    }
                })
                .setEndpoint(endPoint)
                .build();
        T service = restAdapter.create(clazz);

        return service;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM