Reputation: 5247
I'm new to Rx world and I've seen multiple example of how to dispose of a Disposable
but I don't quite understand the difference. I'm using RxJava 2.0 (v2.2.17) and RxAndroid (v2.1.1).
My question is what's the difference between case 1 and case 2 ? Which one of those two cases to prefer in your application ?
Case 1:
private val compositeDisposable: CompositeDisposable = CompositeDisposable()
adsApiService.getVideos()
.subscribeOn(Schedulers.io())
.observeOn( AndroidSchedulers.mainThread())
.subscribe(
{ v -> Log.d("video", v.toString()) },
{ e -> Log.d("video", e.toString()); compositeDisposable.dispose() },
{ compositeDisposable.dispose() },
{ disposable -> compositeDisposable.add(disposable)}
)
}
Case 2:
class MainActivity : AppCompatActivity() {
private var compositeDisposable: CompositeDisposable? = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
compositeDisposable?.add(api.getVideosAds())
}
override fun onDestroy(){
super.onDestroy()
compositeDisposable?.dispose()
}
}
Upvotes: 0
Views: 1387
Reputation: 7788
Personally? Neither.
You should learn how to use ViewModel
s, and keep your CompositeDisposable
there, and clear it in onCleared()
method.
Also, there are some problems with your examples:
Case 1
You should simply add disposable to compositeDisposable
, not sure why you pass 2 additional lambdas to subscribe
:
compositeDisposable += adsApiService.getVideos()
.subscribeOn(Schedulers.io())
.observeOn( AndroidSchedulers.mainThread())
.subscribe(
{ v -> Log.d("video", v.toString()) },
{ e -> Log.d("video", e.toString()) }
)
In this case, you actually don't clear correctly the compositeDisposable
, because it's not attached to any lifecycle (Activity
, Fragment
, or ViewModel
)
Case 2
No need for question mark in statement:
private var compositeDisposable: CompositeDisposable? = CompositeDisposable()
This example is semantically correct, although api
should be hidden in ViewModel
(MVVM architecture) or Presenter
(MVP architecture), or any architecture. Having everything in view class (MainActivity
) is terrible practice and is extra hard to maintain.
Upvotes: 1