OkNet is a wrapper HTTP networking library by Retrofit + OkHttp + RxJava for Android. Works on API level 14 or later.
- Features of Retrofit and OkHttp
- Method Chaining by RxJava
- Support calling in both Kotlin and Java
- Automatically invoke response callback on Android Main Thread while HTTP networking on IO Thread
- Support custom OkHttp Client and Retrofit
- Support maintaining multiple Retrofit object
- High-efficiency GsonConverterFactory and RxJava2CallAdapterFactory
- More coming soon!
repositories {
jcenter()
}
implementation 'com.danke.android:oknet:x.y.z'
- Kotlin
// get
apiService.get()
.compose(MyTransformer<Response<MyResponse>, MyResponse>())
.map { it.data }
.subscribeWith(object : ToastObserver<String>(context){
override fun onNext(t: String) {
// do something when it is successful
}
override fun onStart() {
super.onStart()
// do something when it is started
}
override fun onError(t: Throwable) {
super.onError(t)
// do something when it is failed
}
override fun onComplete() {
super.onComplete()
// do something when it is completed
}
override fun onTokenInvalid(e: TokenInvalidException) {
// do something when token is invalid
}
})
- Java
// get
apiService.get()
.compose(new MyTransformer <>())
.map(response -> response.data)
.subscribeWith(new ToastObserver<String>(context) {
@Override
public void onNext(String s) {
// do something when it is successful
}
@Override
protected void onStart() {
super.onStart();
// do something when it is started
}
@Override
public void onError(@NotNull Throwable t) {
super.onError(t);
// do something when it is failed
}
@Override
public void onComplete() {
super.onComplete();
// do something when it is completed
}
@Override
public void onTokenInvalid(@NotNull TokenInvalidException e) {
// do something when token is invalid
}
});
You can make common configuration in Application or MainActivity.
- Kotlin
Base url is necessary
OkNet.apply {
baseUrl = BASE_URL
}
Or custom RetrofitBuilder
OkNet.apply {
retrofitBuilder = RetrofitBuilder(baseUrl = BASE_URL)
.isLoggingEnable(BuildConfig.DEBUG)
.monitor(MyMonitor)
.clientBuilder(MyOkHttpClientBuilder)
.interceptors(MyInterceptor)
.callAdapterFactories(MyCallAdapterFactory)
.converterFactories(MyConverterFactory)
.timeout(timeout)
}
- Java
Base url is necessary
OkNet.setBaseUrl(BASE_URL);
Or custom RetrofitBuilder
OkNet.setRetrofitBuilder(new RetrofitBuilder(BASE_URL)
.isLoggingEnable(BuildConfig.DEBUG)
.monitor(MyMonitor)
.clientBuilder(MyOkHttpClientBuilder)
.interceptors(MyInterceptor)
.callAdapterFactories(MyCallAdapterFactory)
.converterFactories(MyConverterFactory)
.timeout(timeout);
Custom response must extends BaseResponse
- Kotlin
@Keep
data class MyResponse(
@SerializedName("others") val others: String?) : BaseResponse<MyResponseData>()
- Java
@Keep
public class MyResponse extends BaseResponse<MyResponseData> {
@SerializedName("others")
public String others;
}
Service must be an interface, and you should define your apis in service.
- Kotlin
interface ApiService {
@GET("list")
fun getList(@Query("start") start: Int = 0,
@Query("count") count: Int = 10): Observable<Response<MyResponse>>
@FormUrlEncoded
@POST("list")
fun postList(@Field("start") start: Int = 0,
@Field("count") count: Int = 10): Observable<Response<MyResponse>>
@GET("subject/{id}")
fun getSubject(@Path("id") id: Long): Observable<Response<MyResponse>>
}
- Java
public interface ApiService {
@GET("list")
Observable<Response<MyResponse>> getList(@Query("start") int start,
@Query("count") int count);
@FormUrlEncoded
@POST("list")
Observable<Response<MyResponse>> postList(@Field("start") int start,
@Field("count") int count);
@GET("subject/{id}")
Observable<Response<MyResponse>> getSubject(@Path("id") long id);
}
If there are some common business errors to handle, you can do it in your own Transformer witch extends one of BaseObservableTransformer
, BaseFlowableTransformer
, BaseMaybeTransformer
, or BaseSingleTransformer
.
- Kotlin
class MyTransformer<T : Response<R>, R : BaseResponse<*>> : BaseObservableTransformer<T, R>() {
override fun isTokenInvalid(r: R): Boolean = false
override fun isResponseError(r: R): Boolean = r.code != null || r.msg != null
}
- Java
public class DefaultTransformer<T extends Response<R>, R extends BaseResponse<?>> extends BaseObservableTransformer<T, R> {
@Override
public boolean isTokenInvalid(R r) {
return false;
}
@Override
public boolean isResponseError(R r) {
return r.getCode() != null && r.getCode() != -1 || r.getMsg() != null;
}
}
You can define your own Subscriber or Observer to handle reponse, witch extends
BaseSubscriber
or BaseObserver
. Also you can extends ToastSubscriber
or ToastObserver
witch toast error message, so you can only care for your successful response.
A Proguard configuration is provided as part of the library, so you don’t need to add any specific rules to your Proguard configuration.
- Issues are welcome. Please add a screenshot of bug and code snippet.
- Pull requests are welcome. If you want to change API or making something big better to create issue and discuss it first.
This library is licensed under the Apache Software License, Version 2.0.
See LICENSE
for full of the license text.
Copyright (C) 2018 danke77.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.