NetworkOnMainThreadException与Kotlin中的Retrofit和Rxandroid

时间:2018-10-31 12:37:10

标签: kotlin retrofit rx-android

这个问题已经问了很多遍了,但是没有一个解决方案在起作用。我不知道代码是怎么回事。始终显示android.os.NetworkOnMainThreadException

下面的代码是我的ViewModel

class MainActicityViewModel(val context: MainActivity) : BaseObservable() {

val layoutManagerAppointment = LinearLayoutManager(context)
private val appClient = Appclient().getClient(context)
private val apiInterface = appClient.create(ApiInterface::class.java)
var rcyAdapter: RcyAdapter? = null

init {
    getList()
}

fun getList() {
    val observable = apiInterface.getUsers()
    observable.subscribeOn(Schedulers.io()) // i have also registerd for Schedulers.newThread()

    observable.observeOn(AndroidSchedulers.mainThread())
    observable.subscribeWith(object : DisposableObserver<ArrayList<Data>>() {
        override fun onComplete() {
            Toast.makeText(context, "onComplete", Toast.LENGTH_SHORT).show()
        }

        override fun onNext(t: ArrayList<Data>) {

            Log.e("SIZE", "" + t.size)
            Toast.makeText(context, "onNext", Toast.LENGTH_SHORT).show()
        }

        override fun onError(e: Throwable) {
            Toast.makeText(context, "onError", Toast.LENGTH_SHORT).show()
            Log.e("TAG ON ERROR", "" + e)


        }

    })
}

}

下面的代码是Retrofit Client class

class Appclient {

private var retrofit: Retrofit? = null
private val baseUrl = "https://jsonplaceholder.typicode.com"

fun getClient(context: Context): Retrofit {
    //Here a logging interceptor is created
    val interceptor = HttpLoggingInterceptor()
    interceptor.level = HttpLoggingInterceptor.Level.BODY
    val client = OkHttpClient.Builder()
        .addInterceptor(interceptor).build()

    retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .client(client)
        .build()
    return (retrofit)!!
}}

我的改造界面

interface ApiInterface {
@GET("/users")
fun getUsers(): Observable<ArrayList<Data>>}

这是MainActivity

class MainActivity : AppCompatActivity() {

lateinit var vModel: MainActicityViewModel
var mainBinding: ActivityMainBinding? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mainBinding = DataBindingUtil.setContentView(this@MainActivity, R.layout.activity_main)
    vModel = MainActicityViewModel(this@MainActivity)
    mainBinding!!.viewModel = vModel
}}

1 个答案:

答案 0 :(得分:1)

尝试一下...

fun getList() {
    val observable:Observable<ArrayList<Data>>  = apiInterface.getUsers()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeWith(object : DisposableObserver<ArrayList<Data>>() {
            override fun onComplete() {
                Toast.makeText(context, "onComplete", Toast.LENGTH_SHORT).show()
            }

            override fun onNext(t: ArrayList<Data>) {

                Log.e("SIZE", "" + t.size)
                Toast.makeText(context, "onNext", Toast.LENGTH_SHORT).show()
            }

            override fun onError(e: Throwable) {
                Toast.makeText(context, "onError", Toast.LENGTH_SHORT).show()
                Log.e("TAG ON ERROR", "" + e)
            }
        })
    }

在执行RxJava操作时,Observable必须是链调用,因为Observable不是构建器模式。