저는 최근에 반응 형 프로그래밍을 배우기 시작했습니다. Retrofit2를 사용하여 API JSON 파일을 읽을 수 있지만 RxJava2를 사용하여 반응 형 프로그래밍을 사용하여 수행하는 방법을 모릅니다. 링크 나 기성 코드가 있다면 감사 할 것입니다. 나 자신이이 작업을 구현하려고했지만 작동하지 않습니다. https://www.learn2crack.com/2017/11/retrofit-and-rxjava-in-kotlin.html 링크에 따라 모든 작업을 수행 했지만 구독에서 응답 기능을 호출하면 아무것도 작동하지 않습니다. 예를 들어, 표시하려고하는데 아무것도 표시되지 않습니다.
MainActivity 클래스
package com.example.json_rxjava
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.json_rxjava.MODEL.JsonModel
import com.example.json_rxjava.NETWORK.RequestInterface
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : AppCompatActivity() {
private val BASE_URL = "https://learn2crack-json.herokuapp.com/"
private var mCompositeDisposable: CompositeDisposable? = null
private var mJsonModelDataList: ArrayList<JsonModel>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadJSON()
}
private fun loadJSON() {
val requestInterface = Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build().create(RequestInterface::class.java)
mCompositeDisposable?.add( requestInterface.getData()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse)
)
}
private fun handleError(error: Throwable) {
Log.e("ERROR: ", error.localizedMessage)
}
private fun handleResponse(jsonModel: List<JsonModel>) {
Log.e("LOG TEST", "THIS IS RESPONSE")
mJsonModelDataList = ArrayList(jsonModel)
for(i in 0..mJsonModelDataList!!.size-1) {
Log.e("LOG: ", mJsonModelDataList?.get(i)?.name.toString())
}
}
override fun onDestroy() {
super.onDestroy()
mCompositeDisposable?.clear()
}
}
RequestInterface
package com.example.json_rxjava.NETWORK
import com.example.json_rxjava.MODEL.JsonModel
import io.reactivex.Observable
import retrofit2.http.GET
interface RequestInterface {
@GET("api/android")
fun getData(): Observable<List<JsonModel>>
}
JsonModel
package com.example.json_rxjava.MODEL
data class JsonModel(
val version: String,
val name: String,
val apiLevel: String
)
build.gradle에 다음 종속성을 추가했습니다.
//RxJava and Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
AndroidManifest에 다음이 추가되었습니다.
<uses-permission android:name="android.permission.INTERNET"/>
프로그램은 다음을 출력합니다.
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/: HostConnection::get() New Host Connection established 0xa3fc0140, tid 8411
D/: HostConnection::get() New Host Connection established 0xa3fc0500, tid 8460
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xaed85360: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xaed85360: ver 2 0 (tinfo 0xaed831f0)
D/EGL_emulation: eglMakeCurrent: 0xaed85360: ver 2 0 (tinfo 0xaed831f0)
D/EGL_emulation: eglMakeCurrent: 0xaed85360: ver 2 0 (tinfo 0xaed831f0)
문제가 무엇인지 알고 있거나 Kotlin에서 Retrofit2 및 RxJava2를 사용하여 API JSON을 읽는 방법에 대한 링크 또는 기성 코드가 있으면 알려주세요.
아무 일도 일어나지 않는 이유는 초기화하는 것을 잊었 기 때문 mCompositeDisposable
입니다. 따라서 실행할 때마다 mCompositeDisposable?.
mCompositeDisposable이이므로 해당 코드를 건너 뜁니다 null
.
이를 수정하려면 선언을
private val mCompositeDisposable: CompositeDisposable = CompositeDisposable()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다