levibostian / Wendy-Android

Build offline first Android mobile apps. Remove loading screens, perform tasks instantly.
https://levibostian.github.io/Wendy-Android/wendy/
MIT License
64 stars 16 forks source link

Add to documentation recommendation for how to populate dependencies. #41

Closed levibostian closed 6 years ago

levibostian commented 6 years ago

In my AndroidBlanky project today, I created this PendingTask:

class UpdateFcmTokenPendingTask(userId: String): PendingTask(dataId = userId, // userId is the dataId to simply be the unique ID for this task for Wendy to only keep 1 at a time.
        groupId = null,
        manuallyRun = false,
        tag = UpdateFcmTokenPendingTask.TAG) {

    lateinit var userManager: UserManager

    companion object {
        const val TAG = "UpdateFcmTokenPendingTask"

        fun blank(userManager: UserManager): UpdateFcmTokenPendingTask = UpdateFcmTokenPendingTask("").apply {
            this.userManager = userManager
        }
    }

    override fun runTask(): PendingTaskResult {
        // Send up the FCM token to your server
        val fcmToken = userManager.fcmPushNotificationToken

        return PendingTaskResult.SUCCESSFUL
    }

}

As I was writing runTask(), I realized that I had some dependencies that I required. I needed access to userManager. There is no good way to populate dependencies since Wendy is what populates the PendingTasks.

So I got to work to figure this out. At first I thought about giving all PendingTask instances an instance of Application passed to Wendy.init() that you can use to inject dependencies into. However, I didn't like that approach especially because it's assuming that you are using a tool like Dagger for injection.

I thought of using the blank() design pattern because that is called at a later time when Wendy is going to run the task instead of when the task is first being created and added to Wendy.

I like this solution. I want to add it to the docs.