简体   繁体   中英

Is it good practice to pass the context to the domain layer (Use cases) in android

I have a usecase which will use the alarm manger to set a repeatingAlarms and the alarm manger requires a pendingIntent which also needs the context to create object from. Now my question is it a good approach to pass the context to the usecase? if no then what's the solution?

class SetReminderAlarmsUseCase(
    private val hydrateRepository: HydrateRepository,
    private val alarmManager: AlarmManager,
) {

    suspend operator fun invoke(
        wakeUpTime: String,
        sleepTime: String,
        drinkAmount: Int,
        target: Int,
    ) {
        val alarms = getAlarmsList(wakeUpTime, sleepTime, drinkAmount, target)
        insertAlarms(alarms)

        alarms.forEach { alarm ->
            alarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP,
                getAlarmTime(alarm),
                AlarmManager.INTERVAL_DAY,
                pendingIntent
            )
        }
    }

Use cases are related to clean architecture

https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html

So as per the image - the Use Cases wrap your core business logic. It should be abstract like: "do some generic work".No concrete stuff like Context, AlarmManager, etc. As you can see - the Framework is on the outside.

But how do you call "inside stuff" from the outside when the "inside stuff" depends on the "outside stuff".

This is the central concept behind Clean Architecture: You use interfaces. Dependency inversion.

In your case you need to have something in the "entities layer" that is called for example: ReminderManager. This ReminderManager should be clean Kotlin code. Pure Kotlin code module.

So in the pure Kotlin Module, where the ReminderManager is located, you need to have some interface .

Then you implement the interface in the module where the Framework-related code is located. Whatever implements the interface - it needs to have both context and AlarmManager.

So you see - in the end, the core logic depends on an interface that is located in the same module as the core logic . At the same time, the class that implements the interface is dependent on the interface located in the internal layer. This is how you achieve inversion of control.

I like this example of clean architecture where they use only 2 modules - pure Kotlin code and Framework code.

https://www.raywenderlich.com/3595916-clean-architecture-tutorial-for-android-getting-started

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM