Rxify : The startWith { MVI } pitfall

fun logout(): Observable<ProfileResult> = 
accountService
.logout()
.map { ProfileResult.LogoutSuccess as ProfileResult }
.startWith { ProfileResult.LogoutLoading }
.onErrorReturn { ProfileResult.LogoutFailed(it.message) }

startWith() operator

This operator concats the supplied source of item(s) before it emits other items of this stream.

source

Overridden methods

startWith() operator has the following overridden versions :

  • startWith(ObservableSource<T> source)
  • startWith(T item)
  • startWith(ObservableSource<T> source)
  • map(Function mapper)
  • onErrorReturn(Function valueSupplier)
// from rxjava2public interface ObservableSource<T> {

void subscribe(Observer<? super T> observer);
}
object TestSource: ObservableSource<ProfileResult>() {
override fun subscribe(observer: Observer<ProfileResult>) {
ProfileResult.LogoutLoading
}
}

Corrected Version

fun logout(): Observable<ProfileResult> = 
accountService
.logout()
.map { ProfileResult.LogoutSuccess as ProfileResult }
.startWith ( ProfileResult.LogoutLoading )
.onErrorReturn { ProfileResult.LogoutFailed(it.message) }

TL;DR

Use lambda’s carefully when using with Rx operators.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store