I'll allow myself to insert my five cents: I use jetpack compose for overlay drawing from foreground service + hilt (yeah, it's a modern way). So, I hoped that hiltViewModel
-compose would work, but it didn't ;) In the result I became to create a viewModel manually, like activityViewModel. This is an example of my vision, possible somebody will find it helpful:
abstract class AdvancedLifecycleService : LifecycleService(), SavedStateRegistryOwner, ViewModelStoreOwner {
protected abstract val savedStateRegistryController: SavedStateRegistryController
override val savedStateRegistry: SavedStateRegistry
get() = savedStateRegistryController.savedStateRegistry
override val viewModelStore: ViewModelStore = ViewModelStore()
@Inject
lateinit var overlayViewModelProvider: Provider<OverlayViewModel>
override fun onCreate() {
super.onCreate()
savedStateRegistryController.performRestore(null)
lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (source.lifecycle.currentState == Lifecycle.State.DESTROYED) {
viewModelStore.clear()
source.lifecycle.removeObserver(this)
}
}
})
val a = ViewModelProvider(
store = viewModelStore,
factory = ForegroundViewModelFactory(
overlayViewModelProvider = overlayViewModelProvider,
),
defaultCreationExtras = CreationExtras.Empty
)[OverlayViewModel::class.java]
val b = ViewModelProvider(
store = viewModelStore,
factory = ForegroundViewModelFactory(
overlayViewModelProvider = overlayViewModelProvider,
),
defaultCreationExtras = CreationExtras.Empty
)[OverlayViewModel::class.java]
println("a == b: ${a == b}") // true
}
private class ForegroundViewModelFactory(
private val overlayViewModelProvider: Provider<OverlayViewModel>,) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(OverlayViewModel::class.java)) {
return overlayViewModelProvider.get() as T
} else {
throw IllegalArgumentException("Unknown ViewModel class")
}
}
}
}