Yeah, that's true. One approach is to inject the same scope into viewModel as well and then clear it:
@HiltViewModel
class MainViewModel @Inject constructor(
private val coroutineScope: CoroutineScope,
private val addNotesDelegate: AddNotesDelegate
) :
ViewModel(),
AddNotesDelegate by addNotesDelegate {
override fun onCleared() {
coroutineScope.cancel()
super.onCleared()
}
}
Another approach can be passing the default viewModelScope to the AddNotesDelegateImpl in the init method instead of the constructor. This way we wouldn’t have to create our own custom coroutine scope. Like this:
@HiltViewModel
class MainViewModel @Inject constructor(
private val addNotesDelegate: AddNotesDelegate
) : ViewModel(), AddNotesDelegate by addNotesDelegate {
init {
addNotesDelegate.setCoroutineScope(viewModelScope)
}
}
But both these approaches requires some extra work and negates some of the benefits provided by kotlin delegates I think.