question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

liveData with Coroutines

See original GitHub issue

Hi! who already use for this one androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01 ? I’ve tried it into my repository layer but doesn’t work (i’m using retrofit 2.6.0). this is my code:

interface Service {
     @GET("/data")
     suspend fun getData(): Data
}
class Repository @Inject constructor(val service: Service) {
     fun getData(): LiveData<Data> = liveData {
          val data = service.getData()
          emit(data)
     }
}

and this is my viewmodel:

...
     fun fetch() {
          viewModelScope.launch {
              val data = repository.getData()
              println(data.value)
          }
     }
...

the result is null.

any idea about this? thanks!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6

github_iconTop GitHub Comments

2reactions
alexkazancewcommented, Sep 24, 2019

@GuilhE I think you can do something like this

class SomeViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {

    companion object {
        private const val PAGE_KEY = "page_key"
    }

    private val _page = MutableLiveData<PageId>(savedStateHandle.get(PAGE_KEY))

    private val _itemLiveData = Transformations.switchMap(_page) { pageId -> repository.getNextPage(pageId) }
    val itemLiveData: LiveData<MyItem> = _itemLiveData

    suspend fun nextPage(pageId: PageId) {
        _page.postValue(pageId)
    }

    override fun onCleared() {
        super.onCleared()
        savedStateHandle.set(PAGE_KEY, _page.value)
    }
}

Let me know if it helped you.

1reaction
alexkazancewcommented, Sep 6, 2019

Hi @isfaaghyth . Your liveData from repository.getData() don`t have active observers. So liveData not emiting data. Try something this.

...
     fun fetch():LiveData<Data> {
         return repository.getData(viewModelScope)
          }
     }
...
class Repository @Inject constructor(val service: Service) {
     fun getData(scope:CoroutineScope): LiveData<Data> = liveData(scope.coroutineContext) {
          val data = service.getData()
          emit(data)
     }
}
 class SomeFragment:Fragmet(){
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { ...
        viewModel.fetch().observe(viewLifecycleOwner, Observer{
                 println(it)
      }
  }
}

P.S. Correct me if something is wrong

Read more comments on GitHub >

github_iconTop Results From Across the Web

Use Kotlin coroutines with lifecycle-aware components
The liveData building block serves as a structured concurrency primitive between coroutines and LiveData . The code block starts executing when ...
Read more >
LiveData with Coroutines and Flow — Part II - Medium
This is one of the most common ways to launch a coroutine because most data operations begin in the ViewModel. With the viewModelScope...
Read more >
Coroutines with Lifecycle and LiveData - RayWenderlich.com
In this tutorial, you'll build an Android app that uses coroutines with LiveData objects and lifecycle-aware CoroutineScopes.
Read more >
LiveData with Coroutines (part I - one-shot operations)
LiveData with Coroutines (part II - parameters with switchMap) · LiveData with Coroutines and Flow (Android Dev Summit '19) · Kotlin Andriod MVVM ......
Read more >
LiveData with Coroutines and Flow (Android Dev Summit '19)
LiveData is a simple lifecycle-aware observable, designed for making UIs that react to changes safely and efficiently.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found