What does get() makes difference in SharedFlow if I use in Kotlin Android?

Issue

Is there any difference between this two?

private val _userReviewData = MutableSharedFlow<Resource<ReviewResponse>>()    
val userReviewData get() = _userReviewData.asSharedFlow()

OR

private val _userReviewData = MutableSharedFlow<Resource<ReviewResponse>>()
    val userReviewData = _userReviewData.asSharedFlow()

I don’t understand any diff yet!

Also .asSharedFlow() should I defined explicitly or not?

Solution

When you use get() i.e. provide a custom getter, then every time you access userReviewData, it will call _userReviewData.asSharedFlow() which is unnecessary. It’s better to create a SharedFlow instance once and use it instead of creating multiple such instances.

Answered By – Arpit Shukla

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published