android Jetpack -> Hilt 网络请求 及一些遇到的坑

导入依赖

       //hilt
       hilt_version = '2.29.1-alpha'
       hilt_android = "com.google.dagger:hilt-android:$hilt_version"
       hilt_kapt = "com.google.dagger:hilt-android-compiler:$hilt_version"
       hilt_lifecycle_viewmodel = 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'
       hilt_androidx_kapt = 'androidx.hilt:hilt-compiler:1.0.0-alpha02'

       kapt hilt_kapt
       kapt hilt_androidx_kapt
       api hilt_android
       api hilt_lifecycle_viewmodel

根项目的build文件中添加

      dependencies {
           //其他
           classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
      }

准备工作搞好,本次的网络请求配合retrofit+moshi+viewmodel+livedata+协程使用
本次使用的的API是鸿洋大神的wanandroid.com

1.接口

/**
* wanAndroidApi
*/
interface Api {
   @GET("/wxarticle/chapters/json")
   suspend fun getList(): WanResponse<List<ListResponse>>
}

2.数据仓库

/**
 *  请求来的数据仓库
 */
class HhRepository constructor(private val api: Api) {
    fun getArticle() = flow {
        emit(api.getList())
    }.flowOn(Dispatchers.IO)
}

3.建立retrofit

@Module
@InstallIn(ApplicationComponent::class)
object HiltApi {
    @Provides
    fun provideHhRepository(hhApi: Api) = HhRepository(hhApi)

    @Provides
    fun provideHhApi(retrofit: Retrofit): Api = retrofit.create(
        Api::class.java)

    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit =
        Retrofit.Builder().baseUrl("https://wanandroid.com").client(okHttpClient)
            .addConverterFactory(MoshiConverterFactory.create()).build()

    @Provides
    fun provideOkHttpClient(application: Application) = OkHttpClient.Builder()
        .connectTimeout(1000, TimeUnit.MILLISECONDS)
        .readTimeout(1000, TimeUnit.MILLISECONDS)
        .addInterceptor(HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        })
        .build()
}

4.viewModel

class HiltViewModel @ViewModelInject constructor(
    private val repository: HhRepository,
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    fun getArticle() = liveData {
        repository.getArticle()
            .catch { e ->
                emit(HhResult.Failure(e))
            }
            .collect { it ->
                emit(HhResult.Success(it))
            }
    }
}

5.使用

   private val hiltViewModel: HiltViewModel by viewModels()
    hiltViewModel.getArticle().handleResult(this@Main) {
        onSuccess {
            toast(it.data.toString())
        }
        onFailure {
            toast(it.toString())
        }
    }

handleResult是LiveData的扩展函数

inline fun <E> LiveData<HhResult<E>>.handleResult(
    owner: LifecycleOwner, crossinline handler: HhResultHandler<E>.() -> Unit
) {
    val responseHandler = HhResultHandler<E>().apply(handler)
    observe(owner) {
        when (it) {
            is HhResult.Success -> responseHandler.invokeSuccess(it.value)
            is HhResult.Failure -> responseHandler.invokeFailure(it.throwable)
        }
    }
}

HhResultHandler是在网络请求的基础上封装了一层

class HhResultHandler<T>() {
    private var success: ((T) -> Unit)? = null
    private var failure: ((Throwable) -> Unit)? = null

    infix fun onSuccess(block: (T) -> Unit) {
        success = block
    }

    infix fun onFailure(block: (e: Throwable) -> Unit) {
        failure = block
    }

    fun invokeSuccess(content: T) {
        success?.invoke(content)
    }

    fun invokeFailure(throwable: Throwable) {
        failure?.invoke(throwable)
    }
}

以上呢就是基础的使用啦,下面就是遇到的一些坑
1,组件化开发注解文件不生成问题,在项目所有需要使用的Libaray中都得依赖Hilt

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容