LiveData Transformation to StateFlow / SharedFlow

2.6k Views Asked by At

What is the equivalent code for this live data transformation in StateFlow / SharedFlow?

val myLiveData: LiveData<MyLiveData> = Transformations
                    .switchMap(_query) {
                        if (it == null) {
                           AbsentLiveData.create()
                        } else {
                           repository.load()
                     }

Basically, I want to listen to every query changes to react what to return. So, anything similar to that using StateFlow / SharedFlow is welcome.

2

There are 2 best solutions below

0
Rajan Kali On

switchMap is deprecated in flows and should use either of flatMap, transform or transformLatest to convert one type of flows to others. An example for that would be

val myFlow = flowOf<Int>().transform<Int, String> { flowOf("$it") }} 

I guess you can use same logic for StateFlow or SharedFlows.

0
Sam Chen On

First, create an helper extension function:

fun <R> Flow<R>.toStateFlow(coroutineScope: CoroutineScope, initialValue: R) = stateIn(coroutineScope, SharingStarted.Lazily, initialValue)

Use mapLatest{} for Transformations.map():

val studentNames = _students.mapLatest { students ->
    students.map { "${it.name}" }
}.toStateFlow(uiScope, emptyList())    //uiScope is viewModelScope

Use flatMapLatest{} for Transformations.switchMap():

val asteroids = _asteroidFilter.flatMapLatest { filter ->
    asteroidRepository.getAsteroidsFlow(filter)
}.toStateFlow(uiScope, emptyList())

Use combine() for MediatorLiveData:

val sumScore = combine(_team1Score, _team2Score) { score1, score2 ->
    score1 + score2
}.toStateFlow(uiScope, 0)