Skip to content

Instantly share code, notes, and snippets.

@AchrafAmil
Last active October 11, 2019 09:10
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 AchrafAmil/c115f0f07afc98781cf820ae85976695 to your computer and use it in GitHub Desktop.
Save AchrafAmil/c115f0f07afc98781cf820ae85976695 to your computer and use it in GitHub Desktop.
Android reactive programming sample
import com.jakewharton.rxbinding2.view.clicks
viewModel.bind(follow_button.clicks().map{ ProfileUiEvent.Follow })
viewModel.uiState.observe(this, ::showState)
viewModel.uiContent.observe(this, ::showContent)
sealed class ProfileUiEvent {
data class Show(val userId: String) : ProfileUiEvent()
data class OpenTweet(val tweetId: String) : ProfileUiEvent()
object Follow : ProfileUiEvent()
...
}
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