简体   繁体   中英

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)
}

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.

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