관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[RxJava] Convert Observable to Single (Single.fromObservable) + flatMapCompletable 본문

안드로이드/RxJava

[RxJava] Convert Observable to Single (Single.fromObservable) + flatMapCompletable

막무가내막내 2020. 5. 21. 21:27
728x90
class BachelorNoticeRemoteDataSourceImpl : BachelorNoticeRemoteDataSource {
    override fun requestNotice(): Single<List<BachelorNotice>> {
        return Single.fromObservable(
            Observable.create {
                val bachNoticeList: ArrayList<BachelorNotice> = ArrayList()
                val doc: Document =
                    Jsoup.connect("https://computer.cnu.ac.kr/computer/notice/bachelor.do")
                        .get() // Base Url
                val contentElements: Elements =
                    doc.select("div[class=b-title-box]").select("a") // title, link
                val idElements: Elements = doc.select("td[class=b-num-box]") // id값
                for ((i, elem) in contentElements.withIndex()) {
                    bachNoticeList.add(
                        BachelorNotice(
                            idElements[i].text(),
                            elem.text(),
                            elem.attr("href")
                        )
                    )
                }
                it.onNext(bachNoticeList)
                it.onComplete()
            }
        )
    }

    override fun requestNotice(offset: Int): Single<List<BachelorNotice>> {
        TODO("Not yet implemented")
    }

}

Observable 을 create 하고 Jsoup 통신을 한 뒤 Single로 변환하여 반환해주었습니다.

 

RxJava를 공부하고 입는 입장에서 기록용으로 남깁니다.

 

 


[Single -> Completable 로 전환 이어나가기]

 

 

interface ProfileRepository {
    fun uploadProfileImage(imageUri: Uri?): Single<String>
    fun updateProfileInfo(user: User, imageUrl : String): Completable
}
repository.uploadProfileImage(imageUri = imageUri)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .flatMapCompletable { imageUrl ->
                        repository.updateProfileInfo(user = user, imageUrl = imageUrl)
                    }
                    .doOnSubscribe { showLottieProgress() }
                    .doAfterTerminate { hideLottieProgress() }
                    .subscribeBy(
                        onComplete = {
                            _editProfileSuccess.value = true
                        },
                        onError = {
                            _editProfileSuccess.value = false
                        }
                    )
728x90
Comments