Skip to content

Instantly share code, notes, and snippets.

View Laimiux's full-sized avatar

Laimonas Turauskas Laimiux

View GitHub Profile
interface CommentRepo {
fun submitComment(comment: String): Observable<Lce<Comment>>
}
class CommentViewModel(val model: CommentFormModel) {
fun viewStateStream(): Flowable<CommentFormViewState> {
// define the relays that will allow to complete unidirectional data flow
val textChangedEventRelay = PublishRelay.create<TextChangedEvent>()
val submitEventRelay = PublishRelay.create<SubmitCommentEvent>()
return model
.dataStream(
// We pass the user action flowables to the CommentFormModel
textChangedEvents = textChangedEventRelay.toFlowable(Backpressure.LATEST),
class CommentFormPresenter(val viewModel: CommentViewModel) {
fun attach(view: CommentFormView) {
// Don't forget to unsubscribe
viewModel.viewStateStream().subscribe { state ->
view.setViewState(state)
}
}
}
class CommentFormView(val rootView: View) {
// View binding logic
val commentTextField: EditText = rootView.findViewById(R.id.comment_text_field)
val submitButton: Button = rootView.findViewById(R.id.submit_button)
// Our view update function, takes a view state
// snapshot and updates the android views
fun setViewState(state: CommentFormViewState) {
commentTextField.text = state.textEntered
submitButton.isEnabled = state.isSubmitButtonEnabled
data class CommentFormViewState(
val textEntered: String,
val isSubmitButtonEnabled: Boolean,
val onTextEntered: (String) -> Unit, /* Callback when user modifies the text */
val onSubmitButtonSelected: () -> Unit /* Callback when user clicks submit button */)
fun reduce(event: TextChangedEvent, state: CommentFormData): CommentFormData {
// Let's check comment validity
val isValid = event.enteredText.length > 5
// Update the current state with the changes
return state.copy(comment = event.enteredText, isCommentValid = isValid)
}
class CommentFormModel(val commentService: CommentService) {
fun formState(
textChangedEvents: Observable<TextChangedEvent>,
submitEvents: Observable<SubmitCommentEvent>
) : Observable<CommentFormData> {
// Explicitly declaring the type, for clarity sake
val requestStateEvents: Observable<Lce<Comment>> = submitEvents
.switchMap { event -> commentService.submit(event.comment) }
fun createDataStream(
textChangedEvents: Flowable<TextChangedEvent>,
submitCommentEvents: Flowable<SubmitCommentEvent>
): Flowable<CommentFormData>
fun reduce(event: TextChangedEvent): (CommentFormData) -> CommentFormData {
// implementation
return { state ->
// Let's check comment validity
val isValid = event.enteredText.length > 5
// Update the current state with the changes
return state.copy(comment = event.enteredText, isCommentValid = isValid)
}
}
fun reduce(event: TextChangedEvent): Reducer<CommentFormData> {
// implementation
}
fun reduce(event: Lce<Comment>): Reducer<CommentFormData> {
// implementation
}
fun formState(