preface

Using Retrofit and Rxjava and kotlin-based configuring the web request port, and using the Wikipedia search interface to get the relevant number of search terms: https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=li%20zhaojia

steps

  1. Reference library:
    //Retrofit
    implementation "Com. Squareup. Retrofit2: retrofit: 2.4.0." "
    //Gson converter
    implementation "Com. Squareup. Retrofit2: converter - gson: 2.3.0." "
    //String
    implementation "Com. Squareup. Retrofit2: converter - scalars: 2.3.0." "
    //okhttp
    implementation "Com. Squareup. Okhttp3: okhttp: 3.10.0"
    implementation "Com. Squareup. Okhttp3: logging - interceptor: 3.8.0." "
    //Rxjava
    implementation "Com. Squareup. Retrofit2: adapter - rxjava2:2.4.0." "
    //Rxjava2
    implementation "IO. Reactivex. Rxjava2: rxandroid: 2.0.2"
    implementation "IO. Reactivex. Rxjava2: rxjava: 2.1.9"
Copy the code
  1. Creating a Service Interface
interface WikiApiService{
    @GET("api.php")
    fun hitCountCheck(@QueryMap options:Map<String,String>):Observable<Model.Result>
    //an Observable, which is a Rxjava object that could analog as the endpoint fetcher result generator.
    companion object{
        fun create(a) :WikiApiService{
            val retrofit = Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://en.wikipedia.org/w/")
                .build()
            return retrofit.create(WikiApiService::class.java)}}}Copy the code

Since there are a few variables that need to be query, we use QueryMap to manage variables uniformly and define a HashMap in the activity. Observable returns an object, a class we define to get data, because we want to get data like this:

{
 batchcomplete: "",
 continue: {
  sroffset: 10,
  continue: "-||"
 },
 query: {
  searchinfo: {
   totalhits: 16776   //target data
 },
 search: [...
Copy the code
  1. Create a data index object

Totalhits: results -> query -> searchinfo -> Totalhits

object Model {
    data class Result(val query: Query)
    data class Query(val searchinfo: SearchInfo)
    data class SearchInfo(val totalhits: Int)}Copy the code
  1. Created using lazy loading in the ActivityobservableInstance and create cancelabledisposable:
private var disposable: Disposable? = null   // disposable is a cancelable object
private val wikiApiServe by lazy {
    WikiApiService.create()
}
Copy the code

Then create the function function:

@SuppressLint("SetTextI18n")
private fun beginSearch(srsearch : String){
    val options = HashMap<String,String>()
    options["action"] = "query"
    options["format"] = "json"
    options["list"] = "search"
    options["srsearch"] = srsearch
    //Scheduler: Thread control
    disposable = wikiApiServe.hitCountCheck(options)
        .subscribeOn(Schedulers.io())  //subscribeOn(): Select a Thread to produce I/O scheduler: (read&write data, read&write DB, change info on the Internet)
        .observeOn(AndroidSchedulers.mainThread())  / / observeOn () : choose a Thread to spend AndroidSchedulers. MainThread (), on the Android UI (main Thread)
        .subscribe(
            { result -> show_result.text = "${result.query.searchinfo.totalhits} results found"},
            { error -> Toast.makeText(this, error.message, Toast.LENGTH_LONG).show()}
        )
}
Copy the code

Use this function in the desired Edit text to obtain the number of search terms in the Wikipedia.

get_result.setOnClickListener {
    val text = edit_text.text.toString()
    if (edit_text.text.toString().isNotEmpty()){
        Toast.makeText(this, edit_text.text.toString(), Toast.LENGTH_LONG).show()
        beginSearch(text)
    }
}
Copy the code

conclusion

Can’t change the UI in the points thread, that is to say, must be in the UI thread (AndroidSchedulers. MainThrea ()) to change in the UI layout.

The method to create the interface service can be created in the interface or in the Activity, where you need to use the Companion Object, and then instantiate it in the Activity.