End flow/coroutines task before go further null issue
First of all, don't use GlobalScope
to launch a coroutine, it is highly discouraged and prone to bugs. Use provided lifecycleScope
in Fragment
:
lifecycleScope.launch {...}
Use MutableSharedFlow
instead of MutableStateFlow
, MutableSharedFlow
doesn't require initial value, and you can get rid of nullable generic type:
val pictureElement = MutableSharedFlow<InspirationQuotesDetailsResponse>()
But I guess we can get rid of it.
Method create()
in GetRandomPictureItemUseCase
returns a Flow
that emits only one value, does it really need to be Flow
, or it can be just a simple suspend
function?
Assuming we stick to Flow
in GetRandomPictureItemUseCase
class, ViewModel
can look something like the following:
val randomPicture: Flow<InspirationQuotesDetailsResponse> = getRandomPictureItemUseCase.build(Unit)
And in the Fragment
:
private fun makeApiRequest() = lifecycleScope.launch {
vm.randomPicture
.flowWithLifecycle(lifecycle, State.STARTED)
.collect { response ->
// .. use response
}
}
Dependency to use lifecycleScope
:
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'