Does Retrofit make network calls on main thread?

前端 未结 3 792
轮回少年
轮回少年 2020-11-30 01:03

I am trying to explore Retrofit+OkHttp on Android. Here\'s some code I found online :

RestAdapter restAdapter = new RestAdapter.Builder().setExecutors(execu         


        
3条回答
  •  醉酒成梦
    2020-11-30 01:46

    Kotlin Coroutines

    When using a suspend function to make a network request, Retrofit uses a Coroutine CallAdapter to dispatch on a worker thread.

    Therefore, a coroutine does not need to be explicitly launched on the Dispatcher.IO thread.

    See Android documentation: Page from network and database > Implement a RemoteMediator

    Sample

    Injection.kt

    object Injection {
        val feedService = Retrofit.Builder()
            .baseUrl(TWITTER_API_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(FeedService::class.java)
    }
    

    FeedService.kt

    interface FeedService {
        // Retrofit makes the request on a background thread.
        @GET("lists/{listType}")
        suspend fun getTweets(
            @Path(LIST_TYPE_PATH) listType: String,
            @Query(LIST_ID_QUERY) listId: String,
            @Query(LIST_COUNT_QUERY) count: String,
            @Query(LIST_PAGE_NUM_QUERY) page: String
        ): List
    }
    

    FeedPagingSource

    class FeedPagingSource : PagingSource() {
        override suspend fun load(params: LoadParams): LoadResult {
            try {
                // The results are returned on the main thread.
                val tweets: List = Injection.feedService.getTweets(...)
                return LoadResult.Page(...)
            } catch (error: Exception) { ... }
        }
    }
    

提交回复
热议问题