android Jetpack -> Hilt 網(wǎng)絡(luò)請求 及一些遇到的坑

導(dǎo)入依賴

       //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

根項(xiàng)目的build文件中添加

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

準(zhǔn)備工作搞好,本次的網(wǎng)絡(luò)請求配合retrofit+moshi+viewmodel+livedata+協(xié)程使用
本次使用的的API是鴻洋大神的wanandroid.com

1.接口

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

2.數(shù)據(jù)倉庫

/**
 *  請求來的數(shù)據(jù)倉庫
 */
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的擴(kuò)展函數(shù)

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是在網(wǎng)絡(luò)請求的基礎(chǔ)上封裝了一層

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)
    }
}

以上呢就是基礎(chǔ)的使用啦,下面就是遇到的一些坑
1,組件化開發(fā)注解文件不生成問題,在項(xiàng)目所有需要使用的Libaray中都得依賴Hilt

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容