Get Individual item from PagingData Flow

Viewed 180

I am making a recyclerview to display blog posts using Paging 3. The repository returns a Flow object. I want to get the tags associated with each blog post (which is a class member of BlogPost)

```private val _tags = MutableLiveData<Set<String>>()
val tags: LiveData<Set<String>>
    get() = _tags


private val _blogPost = repository.getBlogPosts()
    .map { posts ->
        posts.filter {
            it.tags.contains(_tags.value)
        }
    }

val blogPost: LiveData<PagingData<BlogPost>>
    get() = _blogPost.asLiveData().cachedIn(viewModelScope)

This is how the data class BlogPost looks like:

@JsonClass(generateAdapter = true)
data class BlogPost(
    //store JSON field
    @Json(name = "tags")
    val tags: List<String>,
    @Json(name = "views")
    val views: Int,
    //used to generate url for blog posts
    @Json(name = "_id")
    val id: String,
    @Json(name = "title")
    val title: String,
    @Json(name = "timeToRead")
    val readTime: Int,
    @Json(name = "category")
    val category: String,
    @Json(name = "author")
    val author: String,
    @Json(name = "aboutAuthor")
    val aboutAuthor: String,
    @Json(name = "shortDescription")
    val descriptionShort: String,
    @Json(name = "imageurl")
    val imageUrl: String,
    @Json(name = "timestamp")
    val timeStamp: String,
    @Json(name = "__v")
    val v: Int
)

I want to get the list of tags from each post , and update my livedata accordingly , so that the user can select a tag and the filter operation can be applied.

I have tried using the onEach operator(fails), and running a method to get the tags in the filter lambda (this works), but I am not sure if this is the correct way to approach this.

0 Answers
Related