All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.lt.lazy_people_http.call.Call.kt Maven / Gradle / Ivy

package com.lt.lazy_people_http.call

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import io.ktor.client.request.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job

/**
 * creator: lt  2023/3/8  [email protected]
 * effect : 网络请求的默认可调用返回值
 * warning:
 */
interface Call {
    /**
     * 异步请求(使用协程)
     */
    fun enqueue(callback: Callback, scope: CoroutineScope = GlobalScope): Job

    /**
     * 协程请求
     * 注意:协程的失败策略在[LazyPeopleHttpConfig]中配置
     */
    suspend fun await(): T

    /**
     * 自定义一些配置
     */
    fun config(block: HttpRequestBuilder.() -> Unit): Call

    /**
     * 将[Call]转化为[State]
     */
    fun toState(onFailure: ((call: Call, t: Throwable?) -> Unit)? = null): State {
        val state = mutableStateOf(null)
        enqueue(object : Callback {
            override fun onResponse(call: Call, response: T) {
                state.value = response
            }

            override fun onFailure(call: Call, t: Throwable?) {
                onFailure?.invoke(call, t)
            }
        })
        return state
    }

    fun toState(
        defaultValue: T,
        onFailure: ((call: Call, t: Throwable?) -> Unit)? = null
    ): State {
        val state = mutableStateOf(defaultValue)
        enqueue(object : Callback {
            override fun onResponse(call: Call, response: T) {
                state.value = response
            }

            override fun onFailure(call: Call, t: Throwable?) {
                onFailure?.invoke(call, t)
            }
        })
        return state
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy