Skip to content

Commit 93c3857

Browse files
committed
💡: modify some comments
1 parent 5dba368 commit 93c3857

2 files changed

Lines changed: 122 additions & 95 deletions

File tree

hooks/src/commonMain/kotlin/xyz/junerver/compose/hooks/userequest/UseRequestOptions.kt

Lines changed: 35 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import xyz.junerver.compose.hooks.UseThrottleOptions
1111
import xyz.junerver.compose.hooks.userequest.utils.CachedData
1212

1313
/*
14-
Description: 请求参数
14+
Description: Request options for useRequest hook
1515
Author: Junerver
1616
Date: 2024/1/31-9:58
1717
Email: junerver@gmail.com
@@ -25,109 +25,108 @@ internal typealias OnFinallyCallback<TParams, TData> = (TParams?, TData?, Throwa
2525
@Stable
2626
data class UseRequestOptions<TParams, TData> internal constructor(
2727
/**
28-
* 默认 false。 即在初始化时自动执行 requestFn
29-
* 如果设置为 true,则需要手动调用 run
28+
* Default false. Automatically execute requestFn on component mounted.
29+
* If set to true, you need to manually call run
3030
*/
3131
@Stable
3232
var manual: Boolean = false,
3333
/**
34-
* 首次默认执行时,传递给 requestFn 的参数
34+
* Parameters passed to requestFn when executed for the first time by default
3535
*/
3636
var defaultParams: TParams? = null,
3737
/**
38-
* requestFn 执行前触发
38+
* Triggered before requestFn execution
3939
*/
4040
@Stable
4141
var onBefore: OnBeforeCallback<TParams> = {},
4242
/**
43-
* requestFn 成功时触发;参数1:请求返回值,参数2:请求参数
43+
* Triggered when requestFn succeeds; param1: request return value, param2: request parameters
4444
*/
4545
@Stable
4646
var onSuccess: OnSuccessCallback<TParams, TData> = { _, _ -> },
4747
/**
48-
* requestFn 抛出异常时触发
48+
* Triggered when requestFn throws an exception
4949
*/
5050
@Stable
5151
var onError: OnErrorCallback<TParams> = { error, _ -> error.printStackTrace() },
5252
/**
53-
* requestFn 执行完成时触发;参数1:请求参数,参数2:返回值,参数3:异常
53+
* Triggered when requestFn execution completes; param1: request parameters, param2: return value, param3: exception
5454
*/
5555
@Stable
5656
var onFinally: OnFinallyCallback<TParams, TData> = { _, _, _ -> },
5757
/**
58-
* 错误重试次数。如果设置为 -1,则无限次重试。
58+
* Number of error retries. If set to -1, retry infinitely.
5959
*/
6060
@Stable
6161
var retryCount: Int = 0,
6262
/**
63-
* 重试时间间隔,单位为毫秒。
64-
* 如果不设置,默认采用简易的指数退避算法,取 1000 * 2 * retryCount
63+
* Retry time interval in milliseconds.
64+
* If not set, a simple exponential backoff algorithm is used by default, taking 1000 * 2 * retryCount
6565
*/
6666
@Stable
6767
var retryInterval: Duration = Duration.ZERO,
6868
/**
69-
* 轮询间隔,单位为毫秒。如果值大于 0,则处于轮询模式。
69+
* Polling interval in milliseconds. If the value is greater than 0, it is in polling mode.
7070
*/
7171
@Stable
7272
var pollingInterval: Duration = Duration.ZERO,
7373
/**
74-
* 在页面隐藏时,是否继续轮询。如果设置为 false,在页面隐藏时会暂时停止轮询,页面重新显示时继续上次轮询。
74+
* Whether to continue polling when the page is hidden. If set to false, polling will be temporarily stopped when the page is hidden, and will continue the last polling when the page is displayed again.
7575
*/
7676
@Stable
7777
var pollingWhenHidden: Boolean = false,
7878
/**
79-
* 轮询错误重试次数。如果设置为 -1,则无限次
79+
* Number of polling error retries. If set to -1, retry infinitely
8080
*/
8181
@Stable
8282
var pollingErrorRetryCount: Int = -1,
8383
/**
84-
* 通过设置 options.ready,可以控制请求是否发出。当其值为 false 时,请求永远都不会发出。
84+
* By setting options.ready, you can control whether the request is sent. When its value is false, the request will never be sent.
8585
*
86-
* 其具体行为如下:
86+
* Its specific behavior is as follows:
8787
*
88-
* [manual]=false 自动请求模式时,每次 [ready] false 变为 true 时,都会自动发起请求,会带上参数 options.[defaultParams]
89-
* [manual]=true 手动请求模式时,只要 [ready]=false,则通过 run/runAsync 触发的请求都不会执行。
88+
* When [manual]=false (automatic request mode), every time [ready] changes from false to true, a request will be automatically initiated with the parameter options.[defaultParams].
89+
* When [manual]=true (manual request mode), as long as [ready]=false, requests triggered by run/runAsync will not be executed.
9090
*/
9191
var ready: Boolean = true,
9292
/**
93-
* 通过设置 options.[refreshDeps],在依赖变化时, [useRequest] 会自动调用 [Fetch.refresh] 方法,实现刷新(重复上一次请求)的效果。
94-
* 如果设置 options.[manual] = true,则 [refreshDeps] 不再生效
93+
* By setting options.[refreshDeps], when dependencies change, [useRequest] will automatically call the [Fetch.refresh] method to achieve the effect of refreshing (repeating the last request).
94+
* If options.[manual] = true is set, [refreshDeps] will no longer take effect
9595
*/
9696
var refreshDeps: Array<Any?> = emptyArray(),
9797
/**
98-
* 如果存在依赖刷新Action函数,则不执行默认的[Fetch.refresh]函数,改为执行[refreshDepsAction]
98+
* If there is a dependency refresh Action function, the default [Fetch.refresh] function will not be executed, and [refreshDepsAction] will be executed instead
9999
*/
100100
var refreshDepsAction: (() -> Unit)? = null,
101101
/**
102-
* 请求的唯一标识。相同 cacheKey 的数据全局同步(cacheTimestaleTime 参数会使该机制失效
102+
* Unique identifier for the request. Data with the same cacheKey is globally synchronized (cacheTime and staleTime parameters will disable this mechanism)
103103
*/
104104
@Stable
105105
var cacheKey: String = "",
106106
/**
107-
* 设置缓存数据回收时间。默认缓存数据 5 分钟后回收
108-
* 如果设置为 `(-1).seconds`, 则表示缓存数据永不过期
107+
* Set cache data recycle time. By default, cache data is recycled after 5 minutes
108+
* If set to `(-1).seconds`, it means cache data never expires
109109
*/
110110
@Stable
111111
var cacheTime: Duration = 5.minutes,
112112
/**
113-
* 缓存数据保持新鲜时间。在该时间间隔内,认为数据是新鲜的,不会重新发请求
114-
* 如果设置为 `(-1).seconds`,则表示数据永远新鲜
113+
* Cache data freshness time. Within this time interval, the data is considered fresh and no new request will be made
114+
* If set to `(-1).seconds`, it means the data is always fresh
115115
*/
116116
@Stable
117117
var staleTime: Duration = Duration.ZERO,
118118
/**
119-
* 自定义缓存策略,无则采取默认策略
119+
* Custom cache strategy, if none, use default strategy
120120
*/
121121
@Stable
122122
var setCache: ((data: CachedData<TData>) -> Unit)? = null,
123123
@Stable
124124
var getCache: ((params: TParams) -> CachedData<TData>)? = null,
125125
/**
126-
* 通过设置 options.[loadingDelay] ,可以延迟 [FetchState.loading] 变成 true 的时间,有效防止闪烁。
127-
* 例如当一个接口正常会较快返回,我们如果常规使用会出现闪烁。从请求发起后,极快的从 false -> true ->false;
128-
* 我们可以设置一个大于这个返回时长的[loadingDelay],例如[50.milliseconds],这样在50ms内返回的接口,
129-
* 不会引起闪烁。这种闪烁其实还有一种变形场景,例如一个接口会极快返回,我们不希望用户继续快速点击,我们期望
130-
* 将loading延时,增加loading的对外表现时间,这种需求接近于节流,又稍有区别
126+
* By setting options.[loadingDelay], you can delay the time when [FetchState.loading] becomes true, effectively preventing flickering.
127+
* For example, when an interface normally returns quickly, if we use it conventionally, flickering will occur. After the request is initiated, it changes very quickly from false -> true -> false;
128+
* We can set a [loadingDelay] that is greater than this return duration, such as [50.milliseconds], so that interfaces that return within 50ms will not cause flickering.
129+
* This flickering actually has another variant scenario, for example, an interface will return very quickly, we don't want users to continue clicking quickly, we expect to delay loading and increase the external performance time of loading, this requirement is close to throttling, but slightly different
131130
*/
132131
@Stable
133132
var loadingDelay: Duration = Duration.ZERO,
@@ -141,13 +140,13 @@ data class UseRequestOptions<TParams, TData> internal constructor(
141140
}
142141

143142
/**
144-
* 通过配置参数为 [UseDebounceOptions.wait] 开启防抖功能,默认值为0,不开启防抖
143+
* Enable debounce functionality by configuring [UseDebounceOptions.wait], default value is 0, debounce is not enabled
145144
*/
146145
@Stable
147146
internal var debounceOptions: UseDebounceOptions = UseDebounceOptions.optionOf { wait = Duration.ZERO }
148147

149148
/**
150-
* 通过配置参数为 [UseThrottleOptions.wait] 开启节流功能,默认值为0,不开启节流
149+
* Enable throttle functionality by configuring [UseThrottleOptions.wait], default value is 0, throttle is not enabled
151150
*/
152151
@Stable
153152
internal var throttleOptions: UseThrottleOptions = UseThrottleOptions.optionOf { wait = Duration.ZERO }
@@ -220,7 +219,7 @@ data class UseRequestOptions<TParams, TData> internal constructor(
220219
}
221220

222221
/**
223-
* 使用代理来实现通过函数配置防抖选项
222+
* Use delegate to implement debounce options configuration through functions
224223
*/
225224
private class DebounceOptionsDelegate(
226225
private var configure: UseDebounceOptions.() -> Unit,
@@ -238,7 +237,7 @@ private class DebounceOptionsDelegate(
238237
}
239238

240239
/**
241-
* 使用代理来实现通过函数配置节流选项
240+
* Use delegate to implement throttle options configuration through functions
242241
*/
243242
private class ThrottleOptionsDelegate(
244243
private var configure: UseThrottleOptions.() -> Unit,

hooks/src/commonMain/kotlin/xyz/junerver/compose/hooks/userequest/useRequest.kt

Lines changed: 87 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -38,63 +38,81 @@ typealias ComposablePluginGenFn<TParams, TData> = @Composable (UseRequestOptions
3838
*/
3939

4040
/**
41-
* Description: 一个用来管理网络状态的Hook,它可以非常方便的接入到传统的 retrofit 网络请求模式中。
42-
* 你几乎不需要做任何额外工作,就可以简单高效的在 Compose 中使用网络请求,并将请求数据作为状态,直接驱动UI。
41+
* A hook for managing network request state that can be easily integrated with traditional Retrofit network request patterns.
42+
* You need almost no additional work to use network requests simply and efficiently in Compose,
43+
* and use request data as state to directly drive the UI.
4344
*
44-
* [SuspendNormalFunction]
45-
* 是所有函数的抽象,我们最终通过函数拿到的手动执行函数也是[SuspendNormalFunction]类型的,
46-
* 调用时要传递的是[arrayOf]的参数。
45+
* [SuspendNormalFunction] is an abstraction of all functions. The manual execution function we finally get through the function
46+
* is also of type [SuspendNormalFunction], and the parameters passed when calling are [arrayOf].
4747
*
48-
* 我还额外提供了两个方便的转换函数
49-
* [asNoopFn]、[asSuspendNoopFn],这两个函数可以把任意的Kotlin函数转换成[useRequest]需要的函数。
50-
* 需要注意区分,如果是挂起函数就需要调用[asSuspendNoopFn],否则就使用
51-
* [asNoopFn],通过这个函数我们可以简化普通函数到[SuspendNormalFunction]的包装过程。
48+
* Two convenient conversion functions [asNoopFn] and [asSuspendNoopFn] are also provided,
49+
* which can convert any Kotlin function to the function required by [useRequest].
50+
* Note the distinction: if it is a suspend function, you need to call [asSuspendNoopFn], otherwise use [asNoopFn].
51+
* Through this function, we can simplify the wrapping process from ordinary functions to [SuspendNormalFunction].
5252
*
53-
* 示例代码:
53+
* Example usage:
5454
*
5555
* ```kotlin
56-
* @Parcelize
57-
* data class Resp<T : Parcelable?>(
58-
* val message: String,
59-
* val status: Int,
60-
* val data: T?
61-
* ) : Parcelable
56+
* // Auto request with default parameters
57+
* val (userInfo, loading, error) = useRequest(
58+
* requestFn = { NetApi.userInfo(it) },
59+
* optionsOf = {
60+
* defaultParams = "junerver" // Auto requests must set default parameters
61+
* }
62+
* )
6263
*
63-
* @Parcelize
64-
* data class LoginSucc(
65-
* val expire: String,
66-
* val token: String
67-
* ) : Parcelable
64+
* // Manual request
65+
* val (repoInfo, loading, error, request) = useRequest(
66+
* requestFn = { params: Tuple2<String, String> ->
67+
* NetApi.repoInfo(params.first, params.second)
68+
* },
69+
* optionsOf = {
70+
* manual = true
71+
* defaultParams = tuple("junerver", "ComposeHooks")
72+
* }
73+
* )
6874
*
69-
* interface WebService {
70-
* //登录
71-
* @Headers("Content-Type:application/json;charset=UTF-8")
72-
* @POST("api/cas/login/restful")
73-
* suspend fun login(@Body body: RequestBody): Resp<LoginSucc>
74-
* }
75-
*
76-
* // 自定义一个传递Retrofit接口实例的扩展函数,省去调用 `asSuspendNoopFn` 每次都要传递实例的步骤
77-
* fun <T : Any> KFunction<T?>.asRequestFn()
78-
* = this.asSuspendNoopFn(NetFetchManager.INSTANCE)
79-
*
80-
* // 现在你可以放心的使用状态了,通过解构赋值拿到的 data 可以直接应用在 Compose UI 中
81-
* val (data, loading, err, run) = useRequest(
82-
* WebService::login.asRequestFn(),
83-
* optionsOf {defaultParams = arrayOf(bodyreq)}
84-
* )
75+
* // Using asSuspendNoopFn for direct function reference
76+
* val (userInfo, loading, error) = useRequest(
77+
* requestFn = NetApi::userInfo.asSuspendNoopFn(),
78+
* optionsOf = {
79+
* defaultParams = tuple("junerver")
80+
* }
81+
* )
8582
* ```
8683
*
87-
* 是的,它可以简单到只有一行代码,通过[UseRequestOptions]选项配置,你可以设置:手动请求、Ready、错误重试、
88-
* 生命周期回调、轮询、防抖、节流、依赖刷新等待功能。
84+
* Through [UseRequestOptions] configuration, you can set: manual request, ready state, error retry,
85+
* lifecycle callbacks, polling, debounce, throttle, dependency refresh and other functions.
8986
*
90-
* Tips: 强烈建议开启Android Studio中类型镶嵌提示,位于:Editor - Inlay Hints - Types -
91-
* Kotlin,它可以 更高效的提示我们解构赋值后拿到的相关状态、函数的类型。
87+
* Tips: It is strongly recommended to enable type inlay hints in Android Studio, located at:
88+
* Editor - Inlay Hints - Types - Kotlin, which can more efficiently prompt us about the types of
89+
* related states and functions obtained after destructuring assignment.
90+
*
91+
* @param requestFn The abstracted request function: suspend (TParams) -> TData.
92+
* If you don't like using [asSuspendNoopFn], you can also use anonymous [suspend] closures.
93+
* @param optionsOf Configuration factory function for request options, see [UseRequestOptions]
94+
* @param plugins Custom plugins array, pass through arrayOf
95+
* @return [RequestHolder] containing data state, loading state, error state, and control functions
96+
*/
97+
@Composable
98+
fun <TParams, TData : Any> useRequest(
99+
requestFn: SuspendNormalFunction<TParams, TData>,
100+
optionsOf: UseRequestOptions<TParams, TData>.() -> Unit = {},
101+
plugins: Array<ComposablePluginGenFn<TParams, TData>> = emptyArray(),
102+
): RequestHolder<TParams, TData> = useRequestPrivate(
103+
requestFn,
104+
useDynamicOptions(optionsOf),
105+
plugins,
106+
)
107+
108+
/**
109+
* Internal implementation of useRequest hook with full plugin support.
110+
* This function handles the core logic of request management including plugin initialization,
111+
* state management, and request execution.
92112
*
93-
* @param requestFn 经过抽象后的请求函数:suspend (TParams) ->
94-
* TData,如果你不喜欢使用[asSuspendNoopFn],也可以使用匿名 [suspend]闭包。
95-
* @param options
96-
* 请求的配置项,参考[RequestOptions],以及[ahooks-useRequest](https://ahooks.gitee.io/zh-CN/hooks/use-request/index).
97-
* @param plugins 自定义的插件,这是一个数组,请通过arrayOf传入
113+
* @param requestFn The abstracted request function: suspend (TParams) -> TData
114+
* @param options Request configuration options, see [UseRequestOptions]
115+
* @param plugins Custom plugins array, pass through arrayOf
98116
*/
99117
@Composable
100118
private fun <TParams, TData : Any> useRequestPrivate(
@@ -146,20 +164,15 @@ private fun <TParams, TData : Any> useRequestPrivate(
146164
}
147165

148166
/**
149-
* 性能优化版本,[optionsOf] 是一个普通的内联函数,他会在每次组件重组时调用,这回带来一些性能上的损耗,我们可以简单呢的通过 [remember],进行优化。
150-
* 在未来版本将会把原始的直接传递对象这类api转变为私有,只允许通过闭包方式使用。
167+
* Internal implementation function that creates and configures the Fetch instance with plugins.
168+
* This function handles the low-level details of state management, plugin initialization,
169+
* and coroutine scope management for the request lifecycle.
170+
*
171+
* @param requestFn The request function to be executed
172+
* @param options Configuration options for the request behavior
173+
* @param plugins Array of plugins to be applied to the request
174+
* @return Configured Fetch instance ready for use
151175
*/
152-
@Composable
153-
fun <TParams, TData : Any> useRequest(
154-
requestFn: SuspendNormalFunction<TParams, TData>,
155-
optionsOf: UseRequestOptions<TParams, TData>.() -> Unit = {},
156-
plugins: Array<ComposablePluginGenFn<TParams, TData>> = emptyArray(),
157-
): RequestHolder<TParams, TData> = useRequestPrivate(
158-
requestFn,
159-
useDynamicOptions(optionsOf),
160-
plugins,
161-
)
162-
163176
@Composable
164177
private fun <TParams, TData : Any> useRequestPluginsImpl(
165178
requestFn: SuspendNormalFunction<TParams, TData>,
@@ -196,6 +209,21 @@ private fun <TParams, TData : Any> useRequestPluginsImpl(
196209
return fetch
197210
}
198211

212+
/**
213+
* Holder class that encapsulates all the state and control functions returned by useRequest hook.
214+
* This class provides a structured way to access request data, loading state, error state,
215+
* and various control functions for managing the request lifecycle.
216+
*
217+
* @param TParams The type of parameters passed to the request function
218+
* @param TData The type of data returned by the request function
219+
* @property data State containing the response data, null if no data has been loaded yet
220+
* @property isLoading State indicating whether a request is currently in progress
221+
* @property error State containing any error that occurred during the request, null if no error
222+
* @property request Function to manually trigger a request with optional parameters
223+
* @property mutate Function to manually update the data state without making a request
224+
* @property refresh Function to refresh the request using the last used parameters
225+
* @property cancel Function to cancel any ongoing request
226+
*/
199227
@Stable
200228
data class RequestHolder<TParams, TData>(
201229
val data: State<TData?>,

0 commit comments

Comments
 (0)