Kotlin 1.3.72, RxJava2
I have the following code and I am trying to avoid using the !! operator, but not sure why it thinks the value is null and I need to use the safe call operator.
Later on I have to use the !! which is bad practice. Why would this be null, as I have declared anything to be nullable types?
class SharedViewModel : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val imageSubject = BehaviorSubject.create<MutableList<Photo>>()
private val selectedPhotos = MutableLiveData<List<Photo>>()
init {
imageSubject.subscribeBy {
selectedPhotos.value = it
}.addTo(compositeDisposable)
}
fun getSelectedPhotos(): LiveData<List<Photo>> {
return selectedPhotos
}
fun addPhotos(photo: Photo) {
// Not sure why I need the safe-call operator here
imageSubject.value?.add(photo)
// Using the !! is bad practice and would like to avoid it
imageSubject.onNext(imageSubject.value!!)
// This is how I am currently handling it, but just wondering why the value would be null when it is not a nullable type?
if(imageSubject.value != null) {
imageSubject.onNext(imageSubject.value ?: mutableListOf())
}
}
}
=== UPDATE =====
I have made some changes and updated. My final one uses a let.
fun addPhotos(photo: Photo) {
imageSubject.value?.add(photo)
// Original
imageSubject.onNext(imageSubject.value!!)
// First Attempt
if(imageSubject.value != null) {
imageSubject.onNext(imageSubject.value ?: mutableListOf())
}
// Final Attempt
imageSubject.value?.let {
imageSubject.onNext(it)
}
}
Just another question:
Is it good practice to add something into a BehaviourSubject imageSubject.value?.add(photo) and then immediately emit that value using the onNext imageSubject.onNext(it)?