RxJava: Take care of code running on main thread

How can we easily fall into this errors with RxJava

So imagine this two classes:

class UserRepository (
val service: UserService
) {
fun getUser(): Single<User> {
return service.getUser()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
class ProfileViewModel (
val userRepository: UserRepository,
val movieRepository: MovieRepository,
val databaseController: DbController
) {
fun getMovies(): {
service.getUser()
.flatMap { user -> movieRepository.getMoviesFor(user) }
.subscribe({//do stuff})
} fun saveUserToDb() : {
service.getUser()
.doOnNext { user -> databaseController.saveUser(user) }
.subscribe({//do stuff})
}

}

Conclusion

Maybe you are thinking this is an obvious mistake, but on large projects when you usually have to make a change on the ViewModel, surely you will don’t even look the code at the repository layer

--

--

Senior Mobile Engineer at Cognizant Softvision https://twitter.com/4fedee

Love podcasts or audiobooks? Learn on the go with our new app.

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