Skip to content

Instantly share code, notes, and snippets.

@AliAzaz
Last active April 4, 2024 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliAzaz/9cbbef71bd0e9f377661ecaeca88fb81 to your computer and use it in GitHub Desktop.
Save AliAzaz/9cbbef71bd0e9f377661ecaeca88fb81 to your computer and use it in GitHub Desktop.
Coroutine Dispatcher in a HILT injection Environment
class CoroutineDispatcherHelper : IDispatcher {
override fun dispatcherIO(): CoroutineDispatcher = Dispatchers.IO
override fun dispatcherMain(): CoroutineDispatcher = Dispatchers.Main
override fun dispatcherDefault(): CoroutineDispatcher = Dispatchers.Default
}
@Module
@InstallIn(SingletonComponent::class)
object CoroutineDispatcherModule {
@Singleton
@Provides
fun provideCoroutineDispatcher(): CoroutineDispatcherHelper {
return CoroutineDispatcherHelper()
}
}
interface IDispatcher {
fun dispatcherIO(): CoroutineDispatcher
fun dispatcherMain(): CoroutineDispatcher
fun dispatcherDefault(): CoroutineDispatcher
}
fun <T> MutableLiveData<T>.launchItemInCoroutine(iDispatcher: CoroutineDispatcher, data: T) {
CoroutineScope(iDispatcher).launch {
postValue(data)
}
}
fun <T> SingleLiveEvent<T>.launchItemInCoroutine(iDispatcher: CoroutineDispatcher, data: T) {
CoroutineScope(iDispatcher).launch {
postValue(data)
}
}
fun <T> MutableSharedFlow<T>.launchItemInCoroutine(iDispatcher: CoroutineDispatcher, data: T) {
CoroutineScope(iDispatcher).launch {
emit(data)
}
}
@HiltViewModel
class MainViewModel @Inject constructor(
private val verificationUseCase: VerificationUseCase,
private val dispatcherHelper: CoroutineDispatcherHelper,
) : ViewModel() {
fun verifyAndChangePassword(changePassword: ChangePassword) {
CoroutineScope(dispatcherHelper.dispatcherIO()).launch {
//Implementation here in coroutine environment
}
}
}
@raheemadamboev
Copy link

raheemadamboev commented Apr 4, 2024

You should launch coroutines with viewModelScope if you want to cancel the coroutine when MainViewModel is cleared/destroyed.

  fun verifyAndChangePassword(changePassword: ChangePassword) {
        viewModelScope.launch(dispatcherHelper.dispatcherIO()) {
          //Implementation here in coroutine environment
        }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment