1
0
mirror of https://github.com/KokaKiwi/BarInsta synced 2024-11-14 02:37:30 +00:00

Add username check to prevent unnecessary fetch in ProfileFragmentViewModel

This commit is contained in:
Ammar Githam 2021-07-06 06:22:06 +09:00
parent 0d35f37bbc
commit 65f46e4ca7

View File

@ -49,6 +49,8 @@ class ProfileFragmentViewModel(
private val profileAction = MutableLiveData(INIT) private val profileAction = MutableLiveData(INIT)
private val _eventLiveData = MutableLiveData<Event<ProfileEvent>?>() private val _eventLiveData = MutableLiveData<Event<ProfileEvent>?>()
private var previousUsername: String? = null
enum class ProfileAction { enum class ProfileAction {
INIT, INIT,
REFRESH, REFRESH,
@ -98,8 +100,9 @@ class ProfileFragmentViewModel(
val profile: LiveData<Resource<User?>> = currentUserStateUsernameActionLiveData.switchMap { val profile: LiveData<Resource<User?>> = currentUserStateUsernameActionLiveData.switchMap {
val (currentUserResource, stateUsernameResource, action) = it val (currentUserResource, stateUsernameResource, action) = it
liveData<Resource<User?>>(context = viewModelScope.coroutineContext + ioDispatcher) { liveData<Resource<User?>>(context = viewModelScope.coroutineContext + ioDispatcher) {
if (action == INIT && previousUsername != null && stateUsernameResource.data == previousUsername) return@liveData
if (currentUserResource.status == Resource.Status.LOADING || stateUsernameResource.status == Resource.Status.LOADING) { if (currentUserResource.status == Resource.Status.LOADING || stateUsernameResource.status == Resource.Status.LOADING) {
emit(Resource.loading(null)) emit(Resource.loading(profileCopy.value?.data))
return@liveData return@liveData
} }
val currentUser = currentUserResource.data val currentUser = currentUserResource.data
@ -111,6 +114,7 @@ class ProfileFragmentViewModel(
try { try {
when (action) { when (action) {
INIT, REFRESH -> { INIT, REFRESH -> {
previousUsername = stateUsername
val fetchedUser = profileFetchControlledRunner.cancelPreviousThenRun { fetchUser(currentUser, stateUsername) } val fetchedUser = profileFetchControlledRunner.cancelPreviousThenRun { fetchUser(currentUser, stateUsername) }
emit(Resource.success(fetchedUser)) emit(Resource.success(fetchedUser))
if (fetchedUser != null) { if (fetchedUser != null) {