简体   繁体   中英

Android + Retrofit2

I have a service, that return Single>

@GET("users/me/favourite-items-by-shop") fun getFavourites(@Header("Authorization") authorization: String?): Single<List<FavouriteItemResponse>>

And I have a repository where i want to get List

override fun getItems(): Single<List<ItemResponse>> {
    return service.getFavourites(token)
            .map(FavouriteItemResponse::items)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
}

But i get i mistake

required:Function<in List<FavouriteItemResponse>!, out (???..???)>!
Found: KProperty1<FavouriteItemResponse, ShopResponse>

How i can fix it?

Try this code to define header it wrong way..

    @Headers("Content-Type:application/json")
@POST(NetworkConstants.WS_SEND_MESSAGE)
Call<MessageResponse> sendMessage(@Body UserData data);

and also you need to define token in all api request then add into retrofit object define time..

    private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (context == null) {
                request = request
                        .newBuilder()
                        .build();
            } else {
                request = request
                        .newBuilder()
                        .addHeader("Authorization", "Bearer " + AppSetting.getStringSharedPref(context, Constants.USER_KEY_TOKEN, ""))
                        .build();
            }
            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}

but this code in java

I can fix it that

return service.getFavourites(token)
                     .map { it[0] }
                     .map { it.items }
                     .subscribeOn(Schedulers.io())
                     .observeOn(AndroidSchedulers.mainThread())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM