SHARE
TWEET

Untitled

a guest Apr 23rd, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top