Skip to content

Commit

Permalink
⚡️: refactor useReducer,the return value is changed from Tuple2 t…
Browse files Browse the repository at this point in the history
…o `Tuple3`, and `dispatchAsync` is added
  • Loading branch information
junerver committed Sep 6, 2024
1 parent 5c2ff82 commit e3f7248
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlin.time.Duration.Companion.seconds
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.mutate
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.plus
import kotlinx.coroutines.delay
import xyz.junerver.compose.hooks.Middleware
import xyz.junerver.compose.hooks.Reducer
import xyz.junerver.compose.hooks.useGetState
Expand Down Expand Up @@ -165,7 +167,7 @@ fun AddTask(onAddTask: (String) -> Unit) {

@Composable
fun TaskApp() {
val (tasks, dispatch) = useReducer<PersistentList<Task>, TaskAction>(
val (tasks, dispatch, dispatchAsync) = useReducer<PersistentList<Task>, TaskAction>(
{ prevState, action ->
when (action) {
is TaskAction.Added -> prevState + Task(nextId++, action.text, false)
Expand All @@ -189,7 +191,10 @@ fun TaskApp() {
)

fun handleAddTask(text: String) {
dispatch(TaskAction.Added(text))
dispatchAsync {
delay(2.seconds)
TaskAction.Added(text)
}
}

fun handleChangeTask(task: Task) {
Expand Down
13 changes: 10 additions & 3 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/useReducer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package xyz.junerver.compose.hooks
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import xyz.junerver.kotlin.Tuple2
import xyz.junerver.compose.hooks.useredux.DispatchAsync
import xyz.junerver.kotlin.Tuple3

/*
Description:
Expand All @@ -30,7 +31,8 @@ fun <S, A> useReducer(
reducer: Reducer<S, A>,
initialState: S,
middlewares: Array<Middleware<S, A>> = emptyArray(),
): Tuple2<S, Dispatch<A>> {
): Tuple3<S, Dispatch<A>, DispatchAsync<A>> {
val asyncRun = useAsync()
var state by _useState(initialState)
val dispatch = { action: A -> state = reducer(state, action) }
val enhancedDispatch: Dispatch<A> = if (middlewares.isNotEmpty()) {
Expand All @@ -44,5 +46,10 @@ fun <S, A> useReducer(
} else {
dispatch
}
return Tuple2(state, enhancedDispatch)
val enhancedDispatchAsync: DispatchAsync<A> = { block ->
asyncRun {
enhancedDispatch(block(enhancedDispatch))
}
}
return Tuple3(state, enhancedDispatch, enhancedDispatchAsync)
}

0 comments on commit e3f7248

Please sign in to comment.