Search code examples
androidkotlinandroid-livedatakotlin-coroutinesandroid-workmanager

Android: Workmanager getWorkInfoByTagLiveData, convert getWorkInfosByTagLiveData to single LiveData


When working with Workmanager, I faced the problem, that I wanted to get a single LiveData Object with the associated tag. My problem was, that Workmanager only provided getWorkInfosByTagLiveData.

Is there a way to get a single LiveData object with the associated tag?


Solution

  • So here is the simple solution:

    Get single WorkInfo as Flow (to observer from ViewModel)

    val singleWorkInfoAsFlow: Flow<WorkInfo> =
        WorkManager.getInstance(context).getWorkInfosByTagLiveData("TAG").asFlow().map { it[0] }
    

    Get single WorkInfo as LiveData (to observe from View)

    val singleWorkInfoAsLiveData: LiveData<WorkInfo> =
        WorkManager.getInstance(context).getWorkInfosByTagLiveData("TAG").map { it[0] }
    

    I know that this was not that hard, but I hope I helped some people with this. If someone knows the java version, just provide it here.

    Cheers