Created
April 18, 2019 05:44
Star
You must be signed in to star a gist
MvRx Counter
This file contains 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
package com.airbnb.mvrx.counter | |
import android.os.Bundle | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import com.airbnb.mvrx.Async | |
import com.airbnb.mvrx.BaseMvRxFragment | |
import com.airbnb.mvrx.Loading | |
import com.airbnb.mvrx.MvRxState | |
import com.airbnb.mvrx.Uninitialized | |
import com.airbnb.mvrx.activityViewModel | |
import com.airbnb.mvrx.withState | |
import com.google.android.material.snackbar.Snackbar | |
import io.reactivex.Observable | |
import kotlinx.android.synthetic.main.fragment_counter.counterText | |
import java.util.concurrent.TimeUnit | |
data class CounterState(val count: Int = 0, val countRequest: Async<Int> = Uninitialized) : MvRxState | |
class CounterViewModel(state: CounterState) : MvRxViewModel<CounterState>(state) { | |
fun incrementCount() = withState { state -> | |
Observable.just(state.count + 1) | |
.delay(1, TimeUnit.SECONDS) | |
.execute { copy(countRequest = it, count = it() ?: count) } | |
} | |
} | |
class CounterFragment : BaseMvRxFragment() { | |
private val viewModel: CounterViewModel by activityViewModel() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
viewModel.asyncSubscribe(CounterState::countRequest, deliveryMode = uniqueOnly(), onFail = { e -> | |
Snackbar.make(containerView, "Failed to load count! ${e.message}", Snackbar.LENGTH_SHORT).show() | |
}) | |
} | |
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { | |
return inflater.inflate(R.layout.fragment_counter, container, false) | |
} | |
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
counterText.setOnClickListener { | |
viewModel.incrementCount() | |
} | |
} | |
override fun invalidate() = withState(viewModel) { state -> | |
counterLoading.isVisible = state.countRequest is Loading | |
if (state.count is Uninitialized) { | |
counterText.text = "Uninitialized" | |
} else { | |
counterText.text = state.count.toString() | |
} | |
} | |
companion object { | |
fun newInstance() = CounterFragment() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment