Skip to content

1.0.3

Compare
Choose a tag to compare
@skydoves skydoves released this 26 Jun 15:24
2e16ec2

🎉 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())
 }