1.0.3
🎉 Released a new version 1.0.3
! 🎉
What's New?
Now Sandwich supports using with coroutines.
We can use the suspend
function on services.
CoroutinesResponseCallAdapterFactory
We can build the Retrofit using with CoroutinesResponseCallAdapterFactory()
call adapter factory.
addCallAdapterFactory(CoroutinesResponseCallAdapterFactory())
And we can use the suspend
keyword in our service.
interface DisneyCoroutinesService {
@GET("DisneyPosters.json")
suspend fun fetchDisneyPosterList(): ApiResponse<List<Poster>>
}
And now we can use like this; An example of using toLiveData
.
class MainCoroutinesViewModel constructor(disneyService: DisneyCoroutinesService) : ViewModel() {
val posterListLiveData: LiveData<List<Poster>>
init {
posterListLiveData = liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emitSource(disneyService.fetchDisneyPosterList()
.onSuccess {
Timber.d("$data")
}
.onError {
Timber.d(message())
}
.onException {
Timber.d(message())
}.toLiveData())
}
CoroutinesDataSourceCallAdapterFactory
We can build the Retrofit using with CoroutinesDataSourceCallAdapterFactory()
call adapter factory.
addCallAdapterFactory(CoroutinesDataSourceCallAdapterFactory())
And we can get the response data as the DataSource
type with suspend
keyword.
interface DisneyCoroutinesService {
@GET("DisneyPosters.json")
suspend fun fetchDisneyPosterList(): DataSource<List<Poster>>
}
Here is an example of the using asLiveData
.
class MainCoroutinesViewModel constructor(disneyService: DisneyCoroutinesService) : ViewModel() {
val posterListLiveData: LiveData<List<Poster>>
init {
Timber.d("initialized MainViewModel.")
posterListLiveData = liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emitSource(disneyService.fetchDisneyPosterList().toResponseDataSource()
// retry fetching data 3 times with 5000L interval when the request gets failure.
.retry(3, 5000L)
.dataRetainPolicy(DataRetainPolicy.RETAIN)
.request {
// handle the case when the API request gets a success response.
onSuccess {
Timber.d("$data")
}
// -- skip --
}.asLiveData())
}