作者:张晓和46872 | 来源:互联网 | 2023-08-31 15:49
长话短说,尝试利用Google的良好做法。我为Di计划使用Dagger 2犯了一个错误。现在我被困住了。我跟随Sunflower architecture
我正在尝试将本地数据(ld)源和远程数据(rd)源分开,同时尽可能保留我拥有的体系结构。我目前有2个数据源ld和rd实现数据源接口。而且我的存储库只能识别该接口中的功能。在googles示例中,它们在两个数据源中共享相同的功能,而我的项目与此不同,它们应该具有不同的功能。 (Ld应该在数据库中插入引号,而远程应该只获取引号)
我尝试创建一个新的接口,该接口实现了数据源,但特定于本地数据源,但是该接口不起作用,请不断从dagger中获取丢失的绑定错误。
Github project
interface QuoteDataSource { //data source interface for both data sources
suspend fun getQuotes(): Result>
}
class DefaultQuoteRepository @Inject constructor(
@Applicationmodule.QuoteRemoteDataSource private val quoteRemoteDataSource: QuoteDataSource,@Applicationmodule.QuoteLocalDataSource private val quoteLocalDataSource: QuoteDataSource,private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : BaseRepository(),QuoteRepository {
@JvmStatic
@Singleton
@QuoteRemoteDataSource
@Provides
fun provideQuoteRemoteDataSource(
jsonNetworkService: JsonNetworkService
): QuoteDataSource {
return QuoteRemoteDataSource(jsonNetworkService.apiService)
}
@JvmStatic
@Singleton
@QuoteLocalDataSource
@Provides
fun provideQuoteLocalDataSource(
database: LocalQuoteDataBase,ioDispatcher: CoroutineDispatcher
): QuoteDataSource {
return QuoteLocalDataSource(
database.quotesDao(),ioDispatcher
)
}
class QuoteLocalDataSource constructor( // for fetching locally stored quotes,might save favorite quootes or save the json quotes
private val quotesDao: QuotesDao,private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : QuoteDataSource {
override suspend fun getQuotes(): Result> = withContext(ioDispatcher) {
return@withContext try {
Success(quotesDao.getQuotes())
} catch (e: Exception) {
Result.Error(IOException("Unable to fetch quotes!"))
}
}
class QuoteRemoteDataSource @Inject constructor(
private val apiService: QuoteApi
) : QuoteDataSource {
override suspend fun getQuotes(): Result> {
val respOnse= apiService.getQuotes().await()
try {
if (response.isSuccessful)
if(!response.body().isnullOrEmpty())
return Result.Success(response.body()) as Result>
return Result.Error(IOException("Error occurred during fetching quotes!"))
} catch (e: Exception) {
Result.Error(IOException("Unable to fetch quotes!"))
}
return Result.Error(IOException("Unable to fetch quotes!"))
}
我正设法使localdata源具有其自己的功能,这些功能可以被默认报价存储库识别。好像我只是将函数添加到本地语言一样,它们对存储库将不可用。