Last active
October 11, 2019 09:10
-
-
Save AchrafAmil/c115f0f07afc98781cf820ae85976695 to your computer and use it in GitHub Desktop.
Android reactive programming sample
This file contains hidden or 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
import com.jakewharton.rxbinding2.view.clicks | |
… | |
viewModel.bind(follow_button.clicks().map{ ProfileUiEvent.Follow }) | |
… | |
viewModel.uiState.observe(this, ::showState) | |
viewModel.uiContent.observe(this, ::showContent) | |
… |
This file contains hidden or 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
sealed class ProfileUiEvent { | |
data class Show(val userId: String) : ProfileUiEvent() | |
data class OpenTweet(val tweetId: String) : ProfileUiEvent() | |
object Follow : ProfileUiEvent() | |
... | |
} |
This file contains hidden or 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
internal class ProfileViewModel @Inject constructor( | |
... | |
getUserInteractor: GetUserInteractor, | |
followUserInteractor: FollowUserInteractor, | |
) : ReactiveViewModel<ProfileUiEvent>() { | |
val uiState: LiveData<UiState> | |
val uiContent: LiveData<ProfileUiModel> | |
init { | |
val userDetailsStream = eventStream | |
.ofType<ProfileUiEvent.Show>() | |
.map { GetUserRequest(it.userId) } | |
.compose(getUserInteractor) | |
val uiContentStream = userDetailsStream | |
.ofType<GetUserRequest.Success> | |
.mapToUserUiModel() | |
val followUserStream = eventsStream | |
.ofType<ProfileUiEvent.Follow>() | |
.withLatestFrom(uiContentStream) | |
.map { (_, uiContent) -> FollowRequest(uiContent.userId) } | |
.compose(followUserInteractor) | |
val uiStateStream = Flowable | |
.merge( | |
userDetailsStream.mapUserState(), | |
followUserStream.mapFollowState() | |
) | |
uiState = fromPublisher(uiStateStream) | |
uiContent = fromPublisher(uiContentStream) | |
} | |
private fun Flowable<FollowResponse>.mapFollowState(): Flowable<UiState> { | |
return this.map { response -> | |
when (response) { | |
is FollowResponse.InFlight -> UiState.Loading | |
is FollowResponse.Error -> UiState.Error(mapError(response)) | |
is FollowResponse.Success -> UiState.Success | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment