Skip to content

Instantly share code, notes, and snippets.

@HarinTrivedi
Last active October 23, 2018 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarinTrivedi/d8c4d306ce7986969dc7d155ee46b547 to your computer and use it in GitHub Desktop.
Save HarinTrivedi/d8c4d306ce7986969dc7d155ee46b547 to your computer and use it in GitHub Desktop.
Example of using Easy.Api with Architecture components ViewModel and LiveData
class UsersFragmentWithViewModel : BaseFragment<FragmentUsersBinding>() {
private lateinit var adapter: UserListAdapter
private lateinit var viewModel: UserViewModel
override fun defineLayoutResource(): Int {
return R.layout.fragment_users
}
override fun initializeComponent(view: View) {
viewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
adapter = UserListAdapter()
binding.rvUsers.adapter = adapter
fetchUsers()
viewModel.usersLiveData.observe(this, Observer<List<User>> { users ->
if (users != null && users.isNotEmpty()) {
hideLoading()
adapter.setUserList(users)
}
binding.executePendingBindings()
})
viewModel.loadingStateLiveData.observe(this, Observer<STATE> { state1 ->
state1?.let {
when (it) {
STATE.SHOW_LOADING -> showLoading()
STATE.HIDE_LOADING -> hideLoading()
STATE.ERROR -> showError("")
STATE.NO_INTERNET -> showNoInternet()
}
}
})
}
}
class UserViewModel(application: Application) : AndroidViewModel(application) {
val usersLiveData: MediatorLiveData<List<User>>
private var usersListApi: EasyApiCall<Envelop<List<User>>>? = null
val loadingStateLiveData: MutableLiveData<STATE> = MutableLiveData()
init {
// initialize live data
usersLiveData = MediatorLiveData()
// set by default null
usersLiveData.value = null
usersListApi = Builder<Envelop<List<User>>>(application)
.attachLoadingLiveData(loadingStateLiveData)
.build()
}
/**
* Api call with EasyApi
* Expose the LiveData Items query so the UI can observe it.
*/
fun fetchUsers(loaderInterface: LoaderInterface) {
usersListApi?.initCall(ApiFactory.instance!!.fetchUsers("1"))!!
.execute(true) { response, isError: Boolean ->
if (!isError)
usersLiveData.value = response?.data
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment