Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. class NewsViewModel : ViewModel(){
  2. //create a new Job
  3. private val parentJob = Job()
  4. //create a coroutine context with the job and the dispatcher
  5. private val coroutineContext : CoroutineContext get() = parentJob + Dispatchers.Default
  6. //create a coroutine scope with the coroutine context
  7. private val scope = CoroutineScope(coroutineContext)
  8. //initialize news repo
  9. private val newsRepository : NewsRepo = NewsRepo(NewsApiService.newsApi)
  10. //live data that will be populated as news updates
  11. val newsLiveData = MutableLiveData<MutableList<Article>>()
  12. fun getLatestNews() {
  13. ///launch the coroutine scope
  14. scope.launch {
  15. //get latest news from news repo
  16. val latestNews = newsRepository.getLatestNews()
  17. //post the value inside live data
  18. newsLiveData.postValue(latestNews)
  19.  
  20. }
  21. }
  22. fun cancelRequests() = coroutineContext.cancel()
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement