Этот вопрос задавался много раз, но ни одно из решений не работает. Я не знаю, что происходит с кодом. Всегда показывает 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
}}