How do i inject viewmodelScope in dagger 2

Viewed 342

I am using dagger 2 with coroutine and paging architecture. I want paging Datasource load with vary viewmodelScope but don't know how to inject viewmodelScope in dagger 2

DataSource. All functions in network and database are suspend function so I must pass a scope.

class NewsDataSource @Inject constructor(
    private val apiService: ApiService,
    private val newsDao: NewsDao,
    private val scope: CoroutineScope
) : PageKeyedDataSource<Int, Article>() {

    private val _listNews = MutableLiveData<PagedList<Article>>()
    val listNews: LiveData<PagedList<Article>>
        get() = _listNews

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, Article>
    ) {
        scope.launch {

            val result = apiService.getNews(1, params.requestedLoadSize)
            when (result) {
                is Result.Success -> {
                    callback.onResult(result.data.articles, null, 2)
                }
            }
        }
    }
}

DataSourceFactory

class NewsDataSourceFactory @Inject constructor(
    private val apiService: ApiService,
    private val newsDao: NewsDao,
    private val scope: CoroutineScope
) : DataSource.Factory<Int, Article>() {
    val newsDataSourceLiveData = MutableLiveData<NewsDataSource>()
    override fun create(): DataSource<Int, Article> {
        val newsDataSource = NewsDataSource(apiService, newsDao, scope)
        newsDataSourceLiveData.postValue(newsDataSource)
        return newsDataSource
    }
}

and my repository

class NewsRepositoryImp @Inject constructor(
    private val newsApi: ApiService,
    private val newsDao: NewsDao,
    private val scope: CoroutineScope
) : INewsRepository {
    override suspend fun getNews(): PagedList<Article> {
        val sourceFactory = NewsDataSourceFactory(newsApi, newsDao, scope)
        val pagedListConfig = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setInitialLoadSizeHint(10)
            .setPageSize(20)
            .build()
        val livePagedList = LivePagedListBuilder(sourceFactory, pagedListConfig).build()
        return livePagedList.value!!
    }
}

How do I pass viewmodelScope for this?

0 Answers
Related