Last active
October 22, 2020 07:30
-
-
Save happy-bracket/8ca92b70d48d2ab4e2680b4ab318061c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class ChatState( | |
val messages: List<Message> = emptyList(), | |
val input: String = "" | |
) | |
sealed class ChatMutation { | |
data class NewMessage(val message: Message) : ChatMutation() | |
data class NewInput(val input: String) : ChatMutation() | |
object SendMessage : ChatMutation() | |
} | |
sealed class ChatEffect { | |
data class SendMessage(val text: String) : ChatEffect() | |
object SubscribeToChat : ChatEffect() | |
} | |
fun ChatState.update(mutation: ChatMutation): Pair<ChatState, Set<ChatEffect>> = | |
when (mutation) { | |
is ChatMutation.NewMessage -> copy(messages = messages + mutation.message) to emptySet() | |
is ChatMutation.NewInput -> copy(input = mutation.input) to emptySet() | |
is ChatMutation.SendMessage -> copy(input = "") to setOf(ChatEffect.SendMessage(input)) | |
} | |
val feature = RxFeature( | |
ChatState(), | |
setOf(ChatEffect.SubscribeToChat), | |
ChatState::update, | |
acquireChatHandler() // omitted, will be covered later | |
) | |
feature.rxState() | |
.observeOn(mainThread()) | |
.subscribe { state -> | |
render(state) | |
} | |
textField.setInputListener { newText -> feature.mutate(ChatMutation.NewInput(newText)) } | |
sendButton.setOnClickListener { feature.mutate(ChatMutation.SendMessage) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment