RxJava Retrofit2 Autocomplete

By | 2021년 11월 5일
Table of Contents

RxJava Retrofit2 Autocomplete

참조1

참조2

참조2 를 기준으로 설명합니다.

참조2에서 설명된 내용은 중복으로 설명하지 않습니다.

의존성 추가

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0"
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'

    implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
}

클라이언트

addCallAdapterFactory 를 추가합니다.

public class MGApiClient {

    private static final String BASE_URL = "https://<API 서버 아이피>/";
    private static Retrofit retrofit;

    public static Retrofit getApiClient() {

        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return  retrofit;
    }
}

인터페이스

Observable 로 변경해 줍니다.

public interface MGApiInterface {

    @GET("v1/esautocomplete/")
    Observable<AutoCompleteResponse> getAutoComplete(
            @Header("Authorization") String token,
            @Query("q") String query,
            @Query("s") int size,
            @Query("p") int page
    );
}

MainActivity

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final long DELAY_IN_MILLIS = 200;
    public static final int MIN_LENGTH_TO_START = 1;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    AutoCompleteTextView searchBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        searchBox       = findViewById(R.id.editTextSearchBox);

        List<String> list = new ArrayList<>();

        searchBox.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, list));

        addOnAutoCompleteTextViewTextChangedObserver(searchBox);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
    }

    private void addOnAutoCompleteTextViewTextChangedObserver(final AutoCompleteTextView autoCompleteTextView) {

        Observable<AutoCompleteResponse> autocompleteResponseObservable =
                RxTextView.textChangeEvents(autoCompleteTextView)
                        .debounce(DELAY_IN_MILLIS, TimeUnit.MILLISECONDS)
                        .map(textViewTextChangeEvent -> textViewTextChangeEvent.text().toString())
                        .filter(s -> s.length() >= MIN_LENGTH_TO_START)
                        .observeOn(Schedulers.io())
                        .switchMap(s -> {
                            return MGApiClient.getApiClient().create(MGApiInterface.class)
                                    .getAutoComplete(
                                    getString(R.string.mgapi_key),
                                    s,
                                    5,
                                    0);
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .retry(1);

        compositeDisposable.add(
                autocompleteResponseObservable.subscribe(
                        autoCompleteResponse -> {
                            List<AutoCompleteItem> list = autoCompleteResponse.getData();

                            List<String> items = new ArrayList<>();
                            for (AutoCompleteItem item : list) {
                                items.add(item.getSearchString());
                            }

                            autoCompleteTextView.setAdapter(new ArrayAdapter<>(this,
                                    android.R.layout.simple_dropdown_item_1line, items));

                            String enteredText = autoCompleteTextView.getText().toString();
                            if (list.size() == 1 && enteredText.equals(list.get(0).getSearchString())) {
                                autoCompleteTextView.dismissDropDown();
                            } else {
                                autoCompleteTextView.showDropDown();
                            }
                        },
                        e -> Log.e(TAG, "onError", e),
                        () -> Log.i(TAG, "onCompleted")));
    }

답글 남기기