Last active
October 23, 2018 07:41
-
-
Save HarinTrivedi/d8c4d306ce7986969dc7d155ee46b547 to your computer and use it in GitHub Desktop.
Example of using Easy.Api with Architecture components ViewModel and LiveData
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
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() | |
} | |
} | |
}) | |
} | |
} |
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
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