Skip to content

Instantly share code, notes, and snippets.

View Laimiux's full-sized avatar

Laimonas Turauskas Laimiux

View GitHub Profile
typealias Reducer<T> = (T) -> T
// User changes text entry
data class TextChangedEvent(val newText: String)
// User clicks create
data class CreateTodoEvent(val text: String)
data class TodoFormState(
val enteredText: String,
// After user clicks create, we send a post request.
val createTodoRequest: CreateTodoRequestState?)
// User can submit the comment
data class SubmitCommentEvent(val comment: String)
sealed class UserEvent {
data class TextChangedEvent(...): UserEvent()
data class SubmitCommentRequestEvent(...): UserEvent()
}
sealed class CommentFormUserEvent {
data class TextChangedEvent(..): CommentFormUserEvent()
data class SubmitCommentRequestEvent(..): CommentFormUserEvent()
}
sealed class LoginFormUserEvent {
// We cannot use TextChangedEvent from CommentFormUserEvent
data class TextChangedEvent(..): LoginFormUserEvent()
data class LoginRequestEvent(..): LoginFormUserEvent()
}
data class CommentFormData(
// defines what user has entered
val comment: String,
// defines if the entered comment is valid for submission
val isCommentValid: Boolean,
// defines if there is a submit request in progress
val submitRequest: Lce<Comment>?
)
// User modifies the comment text field
data class TextChangedEvent(val enteredText: String)
// User clicks submit
data class SubmitCommentEvent(val comment: String)
class CommentFormViewModel {
// Let's create a view state from the data provided.
fun createViewState(
data: CommentFormData,
onTextChanged: (TextChangedEvent) -> Unit,
onSubmitSelected: (SubmitCommentEvent) -> Unit
): CommentFormViewState{
val isSubmitting = data.submitRequest?.let { it.isLoading} ?: false
return CommentFormViewState(
textEntered = data.comment,
fun dataStream(
textChangedEvents: Flowable<TextChangedEvent>,
submitCommentEvents: Flowable<SubmitCommentEvent>
): Flowable<CommentFormData> {
// We need to start with something
val initialFormState = CommentFormData(comment = "", isCommentValid = false, submitRequest = null)
// RxJava scan operator takes initial state and a reduce function
// This operator manages the state for us, where it will keep track
// of the latest state and provide it for next incoming event
return textChangedEvents.scan(initialFormState) { event, currentState ->