Kotlin - Модернизация - rxjava3 - setImage с использованием привязки данных [решено] - PullRequest
0 голосов
/ 19 июня 2020

Я до сих пор не понимаю, почему при успешном вызове Retrofit не отображается изображение, которое вы хотите загрузить. Кто-нибудь из вас может это заметить?

Может быть

зависимости:

    implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
    implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'

здесь Класс ViewModel:

class MainViewModel : ViewModel() {

private val retrofitWorker = RetrofitWorker()

private var byteArray = MutableLiveData<ByteArray?>()

var bitmap: LiveData<Bitmap>? = null

fun getRxImage() {
    retrofitWorker.createService(RetrofitApi::class.java).getImageWithRxJava()
        .doOnSuccess { responseBody ->

            if (responseBody.isSuccessful || responseBody.body() != null || responseBody.errorBody() == null) {
                Log.d("result", "isSuccessful")

                val bytes = responseBody.body()!!.bytes()
                byteArray.postValue(bytes)
                bitmap = Transformations.map(byteArray) {
                    BitmapFactory.decodeByteArray(it, 0, it!!.size)
                }
            }
        }
        .doOnError {
            Log.d("result", "error")
        }
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe()
   }
}

retrofitworkerClass:

class RetrofitWorker {
private val BASE_URL =
    "https://en.wikipedia.org/"

private val retrofit: Retrofit

init {
    retrofit = Retrofit.Builder()
        .client(OkHttpClient())
        .baseUrl(BASE_URL)
        .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
        .build()
}

fun <T> createService(service: Class<T>): T = retrofit.create(service)
}

interface RetrofitApi {
    @GET("wiki/Wikipedia:Extended_image_syntax#/media/File:Westminstpalace.jpg")
    fun getImageWithRxJava(): Single<Response<ResponseBody>>
}

Класс BindingAdapter

@BindingAdapter("imageResult")
fun bindImage(imgView: ImageView, bitmap: Bitmap?) {
bitmap?.let {
    imgView.setImageBitmap(bitmap)
}

}

активность. xml

<data>

    <variable
        name="viewModel"
        type="com.ddd.multithreadcompare.MainViewModel" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
        <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:contentDescription="@string/itsanimage"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/coroutines_button"
        app:layout_constraintHorizontal_bias="0.458"
        app:layout_constraintStart_toStartOf="@+id/rxjava_button"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:imageResult="@{viewModel.bitmap}" />
</androidx.constraintlayout.widget.ConstraintLayout>

Возможно ли, что привязка данных была неправильной? Может где-то не подключен?

Ответы [ 2 ]

0 голосов
/ 19 июня 2020

РЕШЕНИЕ: карта трансформации была неправильным.

Transformations.map(byteArray) {
                    BitmapFactory.decodeByteArray(it, 0, it!!.size)
}

Решение:

private val _bitmap = MutableLiveData<Bitmap>()
val bitmap: LiveData<Bitmap>
    get() = _bitmap

и внутри doSuccess мы можем использовать:

if (responseBody.isSuccessful || responseBody.body() != null || responseBody.errorBody() == null) {
                    val bytes = responseBody.body()!!.bytes()
                    val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                    _bitmap.postValue(bitmap)
                }
0 голосов
/ 19 июня 2020

Может это проблема с вашим url? Вы пробовали использовать окончательный URL-адрес изображения? https://upload.wikimedia.org/wikipedia/commons/3/39/Westminstpalace.jpg

...