I've just learned rxjava, rxkotlin, dagger and retrofit, but I don't know the approach to take when communicating with server/db and how to store information locally. There are 3 questions at the end. Please help
@Singleton
class MyInteractor @Inject constructor() {
@Inject lateinit var context: Context
@Inject lateinit var restClient: RestClient
private var subscriptions: MutableList<Disposable> = mutableListOf()
private var settingsSubject: BehaviorSubject<SettingsDTO> = BehaviorSubject.create()
fun initData() {
initSettings()
}
fun unsubscribeAll() {
subscriptions.forEach({ subscription -> subscription.dispose() })
}
private fun initSettings() {
val settingsObservable = restClient.getSettings()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
val settingsServerSubscription = settingsObservable.subscribe({ response ->
run {
settingsSubject.onNext(response.body())
}
}, {
//TODO handle errors
})
subscriptions.add(settingsServerSubscription)
//subscribe database to subject changes
val settingsDatabaseSubscription = settingsSubject.subscribe { setting ->
//TODO save or update db
}
subscriptions.add(settingsDatabaseSubscription)
}
fun getSettings(callback: SettingsCallback) {
callback.onFetchedSettings(settingsSubject.value)
}
}
- Do I need to save the Disposable subjects and unsubscribe? Or is done automatically? (I'm saving all of the subscriptions in a list then undispose all at once)
- Is this the right approach? I'm initializing all settings in the initData method, and call it at creation of an activity. The data is stored in a behaviour subject (settingsSubject) and I subscribe on that subject to save changes in database, so everytime I want to change a setting I'm calling the rest client and then update the subject (db will be updated because of the subscription)
- On getSettings method, should I use the callback or just return the settingsSubject value?