From b18d90c8422b33d7a58249d04524150b703a220b Mon Sep 17 00:00:00 2001 From: psyrenpark Date: Thu, 29 Feb 2024 16:58:26 +0900 Subject: [PATCH] Update hooks.kt Hello, I've been enjoying using this library. During its use, I've made some modifications. I would appreciate it if you could review them. P.S: I am a React Native developer currently studying Compose and SwiftUI in the React paradigm. --- .../me/pavi2410/useCompose/query/hooks.kt | 46 +++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/query/src/main/java/me/pavi2410/useCompose/query/hooks.kt b/query/src/main/java/me/pavi2410/useCompose/query/hooks.kt index 5d2f0ef..6236d73 100644 --- a/query/src/main/java/me/pavi2410/useCompose/query/hooks.kt +++ b/query/src/main/java/me/pavi2410/useCompose/query/hooks.kt @@ -10,25 +10,32 @@ sealed interface QueryState { data class Content(val data: T) : QueryState } -sealed interface MutationState { +sealed interface MutationState { object Idle : MutationState object Loading : MutationState - data class Error(val message: Throwable) : MutationState - data class Content(val data: T) : MutationState + object Success : MutationState + data class Error(val th: Throwable) : MutationState +// data class Content(val data: T) : MutationState // we unknown callback return type } -interface Mutation { +interface Mutation { fun mutate(vararg args: String, callback: (T) -> Unit) fun cancel() -// val state: MutationState + fun reset() + val state: MutationState } @Composable fun useQuery(query: suspend CoroutineScope.() -> T): State> { return produceState>(initialValue = QueryState.Loading) { value = withContext(Dispatchers.IO) { - val res = query() - QueryState.Content(res) + val res : T + try { + res = query() + QueryState.Content(res) + }catch (e : Exception){ + QueryState.Error(e) + } } } } @@ -36,21 +43,32 @@ fun useQuery(query: suspend CoroutineScope.() -> T): State> { @SuppressLint("ComposableNaming") @Composable fun useMutation(query: suspend CoroutineScope.(args: Array) -> T): Mutation { -// var mutationState by remember { mutableStateOf(MutationState.Idle) } + var mutationState : MutationState by remember { mutableStateOf(MutationState.Idle) } val coroutineScope = rememberCoroutineScope() return object: Mutation { override fun mutate(vararg args: String, callback: (T) -> Unit) { coroutineScope.launch { -// mutationState = MutationState.Loading - callback(query(args)) -// mutationState = MutationState.Success + mutationState = MutationState.Loading + try { + callback(query(args)) + mutationState = MutationState.Success + MutationState.Success + } catch (e : Exception){ + mutationState = MutationState.Error(e) + MutationState.Error(e) + } + } } override fun cancel() { coroutineScope.cancel() } -// override val state: MutationState -// get() = mutationState + override fun reset () { + mutationState = MutationState.Idle + } + + override val state: MutationState + get() = mutationState } -} \ No newline at end of file +}