简介
主要会通过安卓实战来讲解kotlin语法和实际应用,本教程设及知识点包括框架模式mvp+mvvm, Databinding(数据绑定框架),Dagger2(依赖注入框架),DeepLink(页面路由框架),Rxjava,RxAndroid(异步操作框架),Retrofit,Okhtttp等,不过本教程重点在kotlin所以这些框架需要了解可自行百度。
针对人群:Android中级以上,kotlin入门
上一篇文章讲了ApiComponent,现在我们讲ApiModule这个是模块提供器,提供注入时的依赖,下面我们就讲这个接口
都是程序员,直接看代码
**
* Created by bigman 18-05-20
*/
@Module(includes = arrayOf(AppModule::class))
class ApiModule {
@Provides
@Singleton
fun provideRetrofit(baseUrl: HttpUrl, client: OkHttpClient, gson: Gson) =
Retrofit.Builder()
.client(client)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
@Provides
fun provideBaseUrl() = HttpUrl.parse("http://gank.io/api/")
@Provides
fun provideOkhttp(context: Context, interceptor: HttpLoggingInterceptor): OkHttpClient {
val cacheSize = 1024 * 1024 * 10L
val cacheDir = File(context.cacheDir, "http")
val cache = Cache(cacheDir, cacheSize)
return OkHttpClient.Builder()
.cache(cache)
.addInterceptor(interceptor).build()
}
@Provides
fun provideInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor { msg ->
Log.d("okhttp", msg)
}
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
@Provides
fun provideGson() = GsonBuilder().create()
@Provides
fun provideApi(retrofit: Retrofit) = retrofit.create(GankApi::class.java)
}
简单说一下这里的功能,主要为全局提供网络请求框架retrofit,oKHTTP,Gson,还提供了Api接口GankApi
语法点1:kotlin单表达式应用
fun provideBaseUrl() = HttpUrl.parse("http://gank.io/api/")
简单说就是只有一个语句的函数,而且返回就是语句本身,咱们这里ApiModule 还是有好几个例子,大家可以好好看看