在这个使用 dagger2 的示例中,retrofit 如何使用 okhttp 和 gson

How retrofit is using okhttp and gson in this sample using dagger2

这是一个有效的代码

我想了解的是什么: 改造如何使用下面的 okhttpgsonCache 之类的东西....我知道我们注入它但正如 apimodule 中所见,我可以看到有一个全局变量retrofit 在那里使用,但 gsonokhttp 不是全局的

Apimodule.java

@Module
class ApiModule {

    String mBaseUrl;

    ApiModule(String mBaseUrl) {
        this.mBaseUrl = mBaseUrl;
    }


    @Provides
    @Singleton
    Cache provideHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024;
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkhttpClient(Cache cache) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.cache(cache);
        return client.build();
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
    }
}

ApiComponent.java

@Singleton
@Component(modules = {AppModule.class, ApiModule.class})
public interface ApiComponent {
    void inject(MainActivity activity);
}

MyApplication.java

public class MyApplication extends Application {

    private ApiComponent mApiComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        mApiComponent = DaggerApiComponent.builder()
                .appModule(new AppModule(this))
                .apiModule(new ApiModule("https://simplifiedcoding.net/demos/"))
                .build();
    }

    public ApiComponent getNetComponent() {
        return mApiComponent;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //injecting retrofit
    @Inject Retrofit retrofit;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((MyApplication) getApplication()).getNetComponent().inject(this);


        listView = (ListView) findViewById(R.id.listViewHeroes);

        getHeroes();
    }

    private void getHeroes() {
        Api api = retrofit.create(Api.class);
        Call<List<Hero>> call = api.getHeroes();

        call.enqueue(new Callback<List<Hero>>() {
            @Override
            public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
                List<Hero> heroList = response.body();
                String[] heroes = new String[heroList.size()];

                for (int i = 0; i < heroList.size(); i++) {
                    heroes[i] = heroList.get(i).getName();
                }

                listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, heroes));
            }

            @Override
            public void onFailure(Call<List<Hero>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}

你提供OkHttp和Gson给Retrofit Builder,然后Retrofit使用它们进行请求和解析JSON。

当使用 dagger 时,当我们使用 @Provide 时,我们是在告诉 dagger 如何创建特定的 Dependency,然后此依赖项可用于需要该依赖项的任何其他对象。当我们使用 @Inject 时,Dagger 将查看需要什么类型的对象,检查它需要哪些依赖项,如果你试图注入的这个对象需要 dagger 已经知道如何制作的东西(通过用 [= 注释的东西) 14=]) 然后它将为该对象创建一个新的依赖实例,并继续这个过程,直到你通过注入请求的整个对象已经完成。

举个例子:

@Provides
@Singleton
fun provideContext(app: YourApplication): Context = app

@Provides
@Singleton
fun provideDatabase(context: Context): YourAppDb = YourAppDb.create(context)

在此示例中,每当您请求 YourAppDb 的实例时,dagger 将检查其依赖项,看到它需要 context,它将检查它是否 "knows" 如何创建上下文(检查用 @Provides 注释的内容)然后使用此 context 使数据库