Skip to content

Instantly share code, notes, and snippets.

View sanogueralorenzo's full-sized avatar
👋
Hello everyone!

Mario sanogueralorenzo

👋
Hello everyone!
View GitHub Profile
@sanogueralorenzo
sanogueralorenzo / build.gradle
Created March 22, 2018 21:22
ViewModel & LiveData dependencies
dependencies {
//Other dependencies...
implementation "android.arch.lifecycle:extensions:1.1.0"
annotationProcessor "android.arch.lifecycle:compiler:1.1.0"
testImplementation "android.arch.core:core-testing:1.1.0"
}
sealed class ResourceState {
object LOADING : ResourceState()
object SUCCESS : ResourceState()
object ERROR : ResourceState()
}
data class Resource<out T> constructor(
val state: ResourceState,
val data: T? = null,
val message: String? = null
)
class UserListViewModel : ViewModel() {
val users = MutableLiveData<Resource<List<User>>>()
private fun loading() = users.setLoading()
private fun success(userList: List<User>) = users.setSuccess(userList)
private fun error(throwable: Throwable) = users.setError(throwable.message)
}
class CounterViewModel : ViewModel() {
val counter = MutableLiveData<Int>()
var number = 0
fun onButtonClick() = counter.setValue(++number)
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val vm = ViewModelProviders.of(this)[CounterViewModel::class.java]
vm.counter.observe(this, Observer({ textView.text = it.toString() }))
button.setOnClickListener { vm.onButtonClick() }
}
private fun updateUsers(resource: Resource<List<Users>>?) {
resource?.let {
when (it.state) {
ResourceState.LOADING -> loading.visible()
ResourceState.SUCCESS -> loading.gone()
ResourceState.ERROR -> loading.gone()
}
it.data?.let { adapter.addItems(it) }
it.message?.let { snackBar.show() }
}
class CounterViewModelTest {
private lateinit var viewModel: CounterViewModel
@Rule
@JvmField
val instantTaskExecutorRule: TestRule = InstantTaskExecutorRule()
@Before
fun setUp() {
@Singleton
class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T
}
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MapKey
internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
class PostListViewModel @Inject constructor(private val usersPostsUseCase: UsersPostsUseCase) :
ViewModel() {
val posts = MutableLiveData<Resource<List<PostItem>>>()
private val compositeDisposable = CompositeDisposable()
fun get(refresh: Boolean = false) =
compositeDisposable.add(usersPostsUseCase.get(refresh)
.doOnSubscribe { posts.setLoading() }
.subscribeOn(Schedulers.io())