I want to inject analytics or frontPageSection in CustomView. I have achieved parameter(analyticsService) construct using hilt in CustomViews like
@WithFragmentBindings
@AndroidEntryPoint
class MessagesView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0, private val frontPageSection: FrontPageSection = FrontPageSection()) : LinearLayout(context, attributeSet, defStyle),
IPresenceAware by frontPageSection,
IFrontPageSection by frontPageSection, OnItemViewedListener {
@Inject
lateinit var analyticsService: AnalyticsService
}
But as you see IPresenceAware and IFrontPageSection is associated to frontPageSection
. So I must have to implement constructor injection. Now I have two choices to inject analyticsService
to CustomView and pass it to FrontPageSection Or Inject FrontPageSection from DI.
But I need to pass analyticsService
like
FrontPageSection(analyticsService)
FrontPageSection.kt
class FrontPageSection(private val presenceAware: PresenceAware = PresenceAware(),
private val analyticsService: AnalyticsService? = null) : IFrontPageSection, IPresenceAware by presenceAware {
}
IFrontPageSection.kt
interface IFrontPageSection {
fun initSection(viewEventName: String, sortOrderName: SortOrderName, onSectionTrackedListener: OnSectionTrackedListener? = null)
fun isActive(): Boolean
fun setHasContent(hasContent: Boolean)
fun getHasContent(): Boolean
fun getSortOrderName(): SortOrderName
fun getSortOrder(): SortOrder?
fun setSortOrder(sortOrder: SortOrder?)
fun trackSection()
fun acceptsDefaultBackground(): Boolean { return true }
fun debugInfo()
}
PresenceAware.kt
class PresenceAware : IPresenceAware {
private var currentPresence: Presence = Presence.UNSET
override fun changePresence(presence: Presence) {
this.currentPresence = presence
}
override fun getCurrentPresence(): Presence {
return currentPresence
}
}
IPresenceAware.kt
interface IPresenceAware {
fun changePresence(presence: Presence)
fun getCurrentPresence(): Presence
fun isPresent(): Boolean {
return getCurrentPresence() == Presence.FULL_PRESENT
}
fun isHidden(): Boolean {
return getCurrentPresence() == Presence.HIDDEN
}
fun decidingChild(): View? = null
}
Dependency Injection using Hilt
@Module
@InstallIn(SingletonComponent::class)
interface UtilityModule {
@Binds
fun bindFrontPageSection(frontPageSection: FrontPageSection) : IFrontPageSection
@Binds
fun bindPresenceAware(presenceAware: PresenceAware) : IPresenceAware
}
I have seen this answer. I want to achieve this but my class isn't singleton. But it is not working for me