Pratik Butani
Pratik Butani

Reputation: 62419

Android : Best Way to Call Retrofit API on TextChange

I have created one demo to get a list of data from the server using Retrofit. I have 50000+ records.

Now what I have implemented,

A problem that I am facing:

I have heard about Retrofit Caching that may help me but don't know much more about it.

Any other solution to make it more efficient.

Upvotes: 1

Views: 1458

Answers (2)

George Machibya
George Machibya

Reputation: 87

In java I also think the best way is to Use RxJava and RxBinding as follows

 compositeDisposable.add(RxTextView.textChangeEvents(searchEditText)
            .skipInitialValue()
            .debounce(300, TimeUnit.MICROSECONDS)
            .distinctUntilChanged()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<TextViewTextChangeEvent>() {
                @Override
                public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {

adapter.getFilter().filter(textViewTextChangeEvent.getText());
                    Log.d(LOG_TAG, "The value seached "+ textViewTextChangeEvent);
                 //   adapter.notifyDataSetChanged();
                }

                @Override
                public void onError(Throwable e) {
                    Log.d(LOG_TAG, "The error gotten from search: "+ e.getMessage());
                }

                @Override
                public void onComplete() {

                }
            }));
}

Upvotes: 1

Manohar
Manohar

Reputation: 23404

This is what I use with rxjava

create an extension function for AutoCompleteTextView

fun AutoCompleteTextView.addRxTextWatcher(): Observable<String?> {

    val flowable = Observable.create<String?> {
        addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                it.onNext(s?.toString())
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
        })
    }

    return flowable
}

and for AutocompleteTextView add debounce strategy , Here I added time of 400 millisecond , If there is no user input for 400ms then the api request will go . change time according to your requirement

 autocompleteTextView.addRxTextWatcher()
            .debounce(400, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (!TextUtils.isEmpty(it)) {
                    //DO api request
                }
            }

Upvotes: 1

Related Questions