1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/327744707-okhttp-RxHttp

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Это зеркальный репозиторий, синхронизируется ежедневно с исходного репозитория.
Клонировать/Скачать
Внести вклад в разработку кода
Синхронизировать код
Отмена
Подсказка: Поскольку Git не поддерживает пустые директории, создание директории приведёт к созданию пустого файла .keep.
Loading...
README.md

Реализация:

'io.reactivex.rxjava2:rxjava:2.2.8'
'io.reactivex.rxjava2:rxandroid:2.1.1'
'com.github.liujingxing.rxlife:rxlife-rxjava2:2.2.2' //RxJava2, Automatic close request

ksp передаёт версию RxJava:

ksp {
    arg("rxhttp_rxjava", "3.1.6")
}

Kapt передаёт версию RxJava:

kapt {
    arguments {
        arg("rxhttp_rxjava", "3.1.6")
    }
}

javaCompileOptions передаёт версию RxJava:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [
                    rxhttp_rxjava: '3.1.6', 
                ]
            }
        }
    }
}

3. Установка имени пакета класса RxHttp

ksp передаёт имя пакета:

ksp {
     arg("rxhttp_package", "rxhttp.xxx")
}

Kapt передаёт имя пакета:

kapt {
    arguments {
       arg("rxhttp_package", "rxhttp.xxx") 
    }
}

javaCompileOptions передаёт имя пакета:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [
                    rxhttp_package: 'rxhttp.xxx'
                ]
            }
        }
    }
}

Наконец, перестройте проект, что необходимо.

  1. Инициализация SDK. Этот шаг не является обязательным.
RxHttpPlugins.init(OkHttpClient)  
    .setDebug(boolean)  
    .setOnParamAssembly(Consumer)
    ....
  1. Настройка базового URL. Этот шаг не является обязательным.
public class Url {

    //Add the @defaultDomain annotation to BASE_URL
    @DefaultDomain
    public static BASE_URL = "https://..."
}
  1. Выполнение запроса.
// java
RxHttp.get("/service/...")   //1、You can choose get,postFrom,postJson etc
    .addQuery("key", "value")               //add query param
    .addHeader("headerKey", "headerValue")  //add request header
    .toObservable(Student.class)  //2、Use the toXxx method to determine the return value type, customizable
    .subscribe(student -> {  //3、Subscribing observer
        //Success callback,Default IO thread
    }, throwable -> {
        //Abnormal callback
    });

// kotlin 
RxHttp.postForm("/service/...")          //post FormBody
    .add("key", "value")                 //add param to body
    .addQuery("key1", "value1")          //add query param
    .addFile("file", File(".../1.png"))  //add file to body
    .toObservable<Student>()           
    .subscribe({ student ->       
        //Default IO thread
    }, { throwable ->
        
    })

// kotlin coroutine
val students = RxHttp.postJson("/service/...")  //1、post {application/json; charset=utf-8}
    .toAwaitList<Student>()                          //2、Use the toXxx method to determine the return value type, customizable
    .await()                                    //3、Get the return value, await is the suspend method

3. Расширенное использование

  1. Закройте запрос.
//In Rxjava2 , Automatic close request
RxHttp.get("/service/...")
    .toObservableString()
    .as(RxLife.as(this))  //The Activity destroys and automatically closes the request
    .subscribe(s -> {
        //Default IO thread
    }, throwable -> {
        
    });

//In Rxjava3 , Automatic close request
RxHttp.get("/service/...")
    .toObservableString()
    .to(RxLife.to(this))  //The Activity destroys and automatically closes the request
    .subscribe(s -> {
        //Default IO thread
    }, throwable -> {
        
    });


//In RxJava2/RxJava3, close the request manually
Disposable disposable = RxHttp.get("/service/...")
    .toObservableString()
    .subscribe(s -> {
        //Default IO thread
    }, throwable -> {
        
    });

disposable.dispose(); //Close the request at the appropriate time

4. ProGuard

Если вы используете RxHttp v2.2.8 или выше, то сокращение и обфускация будут работать. ## 5. Пожертвования

Если этот проект вам очень помог и вы хотите поддержать разработку и поддержку этого проекта, отсканируйте следующий QR-код для пожертвования. Мы высоко ценим ваше пожертвование. Спасибо!

donations.png

Лицензии

Copyright 2019 liujingxing

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.

Комментарии ( 0 )

Вы можете оставить комментарий после Вход в систему

Введение

30 секунд на запуск, поддержка корутин, RxJava2, RxJava3, самая элегантная в истории реализация загрузки/выгрузки файлов, отслеживания прогресса, динамического и многодоменного кэширования; поддержка сторонних инструментов анализа данных, пользовательских запросов, автоматического закрытия запросов и т. д. Расширить Свернуть
Apache-2.0
Отмена

Обновления

Пока нет обновлений

Участники

все

Недавние действия

Загрузить больше
Больше нет результатов для загрузки
1
https://gitlife.ru/oschina-mirror/327744707-okhttp-RxHttp.git
git@gitlife.ru:oschina-mirror/327744707-okhttp-RxHttp.git
oschina-mirror
327744707-okhttp-RxHttp
327744707-okhttp-RxHttp
master