Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Converting livedata to stateflow

Android, Kotlin

I have the following livedata in my datasource class, I cannot change this to StateFlow, so need to convert it to StateFlow in my viewModel

val trackingCatalogInitialLoadLiveData: LiveData<Pair<CatalogTracking, Int>> by lazy {
    instantSearchDataSourceLiveData.switchMap { instantSearchDataSource ->
        instantSearchDataSource.initialLoadLiveData
    }
}

In My ViewModel I have the following, and this is the part I am not sure about if this is the correct way to convert LiveData to StateFlow:

 val trackingCatalogInitialLoadStateFlow: StateFlow<Pair<CatalogTracking, Int>> by lazy {
        instantSearchDataSourceFactory.trackingCatalogInitialLoadLiveData.asFlow()
            .stateIn(viewModelScope, SharingStarted.Lazily, Pair(CatalogTracking(), 0))
    }

Then in my fragment I just collect the results

coroutineScope.launch {
        mInstantSearchViewModel.trackingCatalogInitialLoadStateFlow.collect { trackingPair ->
           // code here
    }

Is this the best practice to convert LiveData to StateFlow? Anything I should be looking out for?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You don't need to use by lazy. asFlow() and stateIn() both create simple wrappers, so they are trivial to call directly in the property initializer.

As @Joffrey said, if you use SharingStarted.Lazily, inspecting the flow's value before it has any collectors will incorrectly show your provided initial value. Since LiveData is hot, starting your StateFlow lazily doesn't buy you a lot. The underlying coroutine that transfers LiveData values to the StateFlow is doing a trivial amount of work.

If you don't need to inspect the value (in most cases you probably don't), then it should be fine to leave it as a cold Flow. Even though the Flow from asFlow() is cold, the underlying LiveData is still hot, so when collectors of the flow collect it, they'll always get the latest value. The main behavior difference would be if your data source does not provide a guaranteed initial value for the LiveData, then a StateFlow gives you the opportunity to emit your provided default initially without waiting for the LiveData to publish its first value.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!