Skip to content

Quick Start

Miguel Panelo edited this page Feb 10, 2019 · 5 revisions

To create a Kaskade we use the DSL. Below is a sample of Todo app flow

Kaskade.create<TodoAction, TodoState>(TodoState.OnLoaded(listOf())) {
    on<TodoAction.Refresh> {
        TodoState.OnLoaded(todoRepository.getToDoItems())
    }

    on<TodoAction.Delete> {
        todoRepository.removeItem(action.todoItem)
        TodoState.OnDeleted(action.position)
    }

    on<TodoAction.Add> {
        todoRepository.addItem(action.todoItem)
        TodoState.OnAdded(action.todoItem)
    }

    on<TodoAction.Update> {
        todoRepository.updateItem(action.todoItem)
        TodoState.OnUpdated(action.position, action.todoItem)
    }
}

As you can see the it has four Actions and four States which are represented as sealed classes.

sealed class TodoState : State {
    data class OnLoaded(val list: List<TodoItem>) : TodoState()
    data class OnDeleted(val position: Int) : TodoState()
    data class OnAdded(val item: TodoItem) : TodoState()
    data class OnUpdated(val position: Int, val item: TodoItem) : TodoState()
}
sealed class TodoAction : Action {
    object Refresh : TodoAction()
    data class Delete(val position: Int, val todoItem: TodoItem) : TodoAction()
    data class Add(val todoItem: TodoItem) : TodoAction()
    data class Update(val position: Int, val todoItem: TodoItem) : TodoAction()
}

In this example the Reducer is the lambda in the on method. Let's take the Refresh as an example.

on<TodoAction.Refresh> {
    TodoState.OnLoaded(todoRepository.getToDoItems())
}

The reducer simply just outputs a new TodoState.OnLoaded regardless of the previous state. This also runs synchronously. For async operations, Kaskade has modules for RxJava and Coroutines.

Executing Actions

kaskade.process(TodoAction.Refresh)

This sample starts the Kaskade with the action Refresh

Listening to States

kaskade.onStateChanged = {
    render(it)
}

To listen to states we use the onStateChanged function. In this example, every time the client receives a state it calls the render function.

Unsubscribing

Reducers or the onStateChanged function might have strong references, it's always a good idea to dereference them when the Kaskade is no longer needed to prevent memory leaks. Kaskade has a method unsubscribe to do this.

kaskade.unsubscribe()