Beginning RxKotlin · Observables and Subjects in Practice, Part 1 | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/7419-beginning-rxkotlin/lessons/11

Hey, Joe.
Thanks for the excellent course. really enjoying your courses.

my question:
in the RxAndroid GitHub page:

they say:

implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
// Because RxAndroid releases are few and far between, it is recommended you also
// explicitly depend on RxJava's latest version for bug fixes and new features.
// (see https://github.com/ReactiveX/RxJava/releases for latest 2.x.x version)
implementation 'io.reactivex.rxjava2:rxjava:2.x.x'

so should add 3 dependencies for kotlin like so?

implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.10'
implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'

or perhaps the rxkotlin dependency is regularly maintained and already imports the latest version?

Hi @tomer thanks for the kind words!

On your question, there’s a similar comment on the RxKotlin page:

The maintainers do not update the RxJava dependency version for every RxJava release, so you should explicitly add the desired RxJava dependency version to your pom.xml or build.gradle(.kts).

So yes it would be best to explicitly include the RxJava dependency in order to make sure you’re using the version you want. Just watch out for any inconsistencies between the wrapper and the main RxJava library, should they pop up.

Thanks again!

1 Like

For anyone wondering: the example code uses an anti pattern by using mutable lists and updating them – you should use immutable ones. When you’re adjusting the sample that way, make sure to fix the infinite loop bug in the activity this change will unmask.

  private val imagesSubject: BehaviorSubject<List<Photo>>
      = BehaviorSubject.createDefault<List<Photo>>(listOf())

and

  fun addPhoto(photo: Photo) {
    val newValue = imagesSubject.value + photo
    imagesSubject.onNext(newValue)
  }

  fun clearPhotos() {
    imagesSubject.onNext(emptyList())
  }

Additionally the infinite loop in the Activity hides here:

    viewModel.getSelectedPhotos().observe(this, Observer { photos ->
      photos?.let {
        if (photos.isNotEmpty()) {
          val bitmaps = photos.map { BitmapFactory.decodeResource(resources, it.drawable) }
          val newBitmap = combineImages(bitmaps)
          collageImage.setImageDrawable(BitmapDrawable(resources, newBitmap))
        } else {
          actionClear()
        }
      }
    })

This is, because actionClear() tells the ViewModel to clear the elements again which ends up in a recursion.