Loïc Jackotin
Loïc Jackotin

Reputation: 583

Do enqueueUniquePeriodicWork() Work Manager's method works in a Composable Function?

I'm trying to start a periodic task.

The problem is that I need some data to be send to the work manager and this data is only accessible when the user signs in or signs up to my app (those data are userId and userScore). I can't enqueue the worker in the Main Activity because the Main Activity doesn't recompose.

If I call the method enqueueUniquePeriodicWork() in a composable function do he will only start one Work and not start a Work each time the screen recompose?

So I created a ViewModel

@HiltViewModel
class MainActivityViewModel @Inject constructor(
    val workManager: WorkManager
) : ViewModel() {

    
}

with Hilt Module:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideWorkManager(@ApplicationContext applicationContext: Context): WorkManager =
        WorkManager.getInstance(applicationContext)
}

Upvotes: 1

Views: 211

Answers (1)

Nikola Despotoski
Nikola Despotoski

Reputation: 50538

If you don't wrap it in LaunchedEffect your Worker will be enqueued multiple times. What's your ExistingPolicy, is it REPLACE?

I suggest you move this to a viewmodel, or anywhere outside the UI layer.

Upvotes: 1

Related Questions