Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

android - SharedFlow : mapLatest not getting triggered

Let's make this simple. I've one MutableSharedFlow named sortOrder in my ViewModel.

private val sortOrder = MutableSharedFlow<String>(
    replay = 0,
    extraBufferCapacity = 1
)

I've a mapLatest connected to the sortOrder to refresh data whenever the sortOrder changed.

val data = sortOrder.mapLatest {
    Timber.d("Sort order changed to $it")
    "Sort order is $it"
}

I have an observer listening to data in the activity.

viewModel.data.asLiveData().observe(this) {
    Timber.d("onCreate: New data is $it")
}

and finally, I change the sortOrder in ViewModel's init method

init {
    sortOrder.tryEmit("year")
}

but even after changing the sortOrder value, the mapLatest not getting triggered. Any idea why?

I am using MutableSharedFlow to control the replay property to prevent executing mapLatest body every time I rotate the screen (or when the activity recreated).

Full Source Code

PS: I am new to Flow APIs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think tryEmit should be avoided, in cases where you don't have a replay, but still don't want your events to be dropped.

In these cases I'd use emit(), which will suspend until a subscriber, in your case mapLatest comes into play.

Also in case of a screen-rotation, if the event is emitted while the screen is rotating and you're not listening to the event, you'll get it after the screen-rotation, which I believe is the right UX in most of the cases, but it might depend


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...