Kotlin coroutine and RXJAVA analysis and understanding (1)

tags: Coroutine  customize  android  rxjava  kotlin  

What is an coroutine

  • Coroutines is a lighter than a thread. Just as one process can have multiple threads, one thread can have multiple coroutines

  • One thing that must be clear is that the operation of multiple corporations of a thread is serial. If it is a multi -core CPU, multiple processes or multiple threads in one process can run parallel, but an intra -threaded coroutine is It is definitely serial, no matter how many cores of the CPU have. Although the coroutine is a special function after all, it is still a function. Multiple functions can be run in a thread, but these functions are running serialized.

  • When an coroutine runs, other coroutines must be hung.

  • The biggest feature of processing multi -task concurrency is that it can automatically help us switch threads. Simply put, corporate is a thread framework

  • DEVELOPER link

  • Official website link

The relationship between corporation and thread

Council and thread can be used to achieve asynchronous calls, but there are essential differences between the two

  • The coroutine is the compiler level, and the thread is system level. The switching of the coroutine is controlled by the program. The switching of the thread is controlled by the operating system
  • The coroutine is collaborative, and the thread is seized. The coroutine is controlled by the program to switch, and the thread has an operating system to determine the switch between threads.
  • One thread can contain multiple coroutines
  • In Java, multi -threading can make full use of multi -core CPUs. The coroutine is executed in a thread
  • Council is suitable for IO -dense programs, and multi -threading is suitable for calculating dense programs (suitable for multi -core CPUs). When your program is mostly a file read and write operation or network request operation, you should choose the first -choice corporation instead of multi -threaded. First of all, most of these operations are not using the CPU to calculate but wait for the read and write data. The execution efficiency of the coroutine is high. Sub -program switching is not a thread switching, but controlled by the program itself. Therefore, there is no thread switching overhead. Compared with multi -threaded, the more threads, the more obvious the performance advantage of the correction.
  • You can call the asynchronous code in order to use the coroutine to avoid calling back to hell

Council vs rxjava

What are the advantages of corporate compared to RXJAVA?

  • Rxjava stack readability check. Once problems occur, the stack information explosion is difficult to locate the problem, and the coroutine can avoid this problem
  • The coroutine is written in synchronous ways to write asynchronous code.
  • The coroutine learning curve is relatively flat. Compared to RXJAVA, the coroutine is easier for beginners to learn

Rxjava is more powerful than corporate?

  • Rxjava's real scene, for example, at this time a scene is here to load nine pictures, the strange number is blurred, and the number of cyclists. At this time, the Kotlin coroutine is powerless, because it is just an asynchronous tool. Advantages, dealing with asynchronous problems like fish. Rxjava's more embodiment is a programming thinking. You just need to care about what you do, and you don't need to do what you do. The design concept of the two is still very different

Council can support multiple request synchronization or asynchronous treatment like RXJAVA

  • Rxjava multiple requestsConcurrent
    • use flatMap Keywords, code examples
        mViewModel.getOrder(uuid).flatMap {
            mViewModel.queryClient(QueryRequest().apply {
                start = 0
                limit = 20
                filters.add(FilterParam("keyword:%=%", it.data?.customerName))
            })
        }.flatMap {
            if (it.data?.size == 0) {
                throw Throwable("Throwing abnormal here")
            } else {
                setCurClientData(ChooseClientWrapper(it.data?.get(0)))
            }
            mViewModel.queryGoods(QueryRequest().apply {
                filters.add(FilterParam("shopId:=", StorageMgr.getConfig(Constants.PS4_WosShop)))
                filters.add(FilterParam("customerId:=", mViewModel.curClient.get().data?.code))
                filters.add(FilterParam("wrhId:=", mViewModel.curWrh.get().data?.uuid))
                filters.add(FilterParam("skuId:in", arrayListOf<String>().apply {
                    mViewModel.goodsLines.forEach { goodsLine ->
                        add(goodsLine.gdGid.toString())
                    }
                }))
            })
        }
            .doOnSubscribe { showLoading() }
            .doAfterTerminate { hideLoading() }
            .bindLifeCycle(this)
            .subscribe({},{})
  • Rxjava multiple requestsSynchronous and orderly
    • use concatMap Keywords, code examples
    • .map is a successful triggering of each interface, .count () is to ensure that all interfaces go synchronously.
 mViewModel.listPictureParam.clear()
        Observable.fromIterable(mViewModel.listPictureCompress).concatMap {
            mViewModel.uploadImage(BOssImage().apply {
                name = FileUtils.getFileNameWithSuffix(it)
                ext = FileUtils.getSuffix(it)
                bytes = Base64.encodeToString(FileUtils.file2byte(it), Base64.DEFAULT)
            }).toObservable()
        }.map {
            mViewModel.listPictureParam.add(it.data?.url)
        }.count().flatMap {
            mViewModel.deliver(RfOrderDeliverReq().apply {
                orderId = mViewModel.uuid.get()
                if (mViewModel.carNumEdit.get() != null) {
                    carNumber = mViewModel.carNumEdit.get().trim()
                }
                if (mViewModel.remarkEdit.get() != null) {
                    remark = mViewModel.remarkEdit.get().trim()
                }
                vouchers.addAll(mViewModel.listPictureParam.map { it })
            })
        }.doOnSubscribe { showLoading() }
            .doAfterTerminate { hideLoading() }
            .bindLifeCycle(this)
            .subscribe({},{})
  • Council requests more requests to be supplemented by follow -up

How to use corporation

  • Add dependence
       // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2' 
  • Start a coroutine
CoroutineScope(Dispatchers.Main).launch{
}
  • Hanging function

It involves 2 new things here, the first issuspend The modification character, the other iswithContext function
The role of the Suspend is that the logo method is the function of hanging the function, which is modified as a function of the hanging function.Can only be called in the coroutine or other hanging functions
The role of the WithContext function is to switch threads. You can see Dispatches.io later, that is, I switched to the IO thread
In this way, the hung function can be cut to other threads to execute, and after the execution, the main thread that returns to Launch continues to execute, and the effect of automatic switching thread

    private suspend fun getData(): String {
        return withContext(Dispatchers.IO) {
            "hen_coder"
        }
    }

How to replace the rxjava request interface in the project with the subsequent update

Intelligent Recommendation

Kotlin Coroutine Part 1

What is a coroutine Coroutine is a set of thread-encapsulated API provided by Kotlin In Kotlin, a typical use scenario for coroutines is thread control What's so good about the coroutine In Kotlin, wh...

Kotlin Coroutine (1)

   I started to learn things related to cooperation in summer vacation. At the beginning, I looked confused, and then I repeated the cycle of understanding -> eh what is going on -> look again -...

Probe into Kotlin Coroutine (1)

Probe into Kotlin Coroutine (1) 2017, Google announcedKotlin Become an official development language of Android and adds support for COROUTINE (equation, simply as a lightweight thread) at version 1.1...

Deep understanding of Kotlin coroutine (2)

Last week we talked about Kotlin Coroutine's basic API and gave some simple packages. I don’t want to give it too much. Just in the 1.1 Beta 2 released a few days ago, all the coroutine API pack...

In -depth understanding of the Koltin coroutine (1): Why do you learn the Kotlin coroutine?

Series e -book:Portal Why learn Kotlin coroutines? We already have a very complete type of JVM library, such as RXJAVA and Reactor. In addition, Java itself supports multi -threaded threads, and most ...

More Recommendation

Kotlin Coroutines (coroutine) complete analysis (a), introduction to the coroutine

Kotlin Coroutines (Coroutine) Completely Analytical Series: Kotlin Coroutines (coroutine) complete analysis (a), introduction to the coroutine Kotlin Coroutines (coroutine) complete parsing (2), deep ...

Analysis of kotlin coroutine source code

Foreword Kotlin is now a fresher language. I have asked friends around me, and some seem to start using them to start writing backgrounds, and some start to refactor Android project code with kotlin. ...

Kotlin coroutine bytecode parsing -1

Background Kotlinx.coroutines is a feature-rich coroutine library developed by JetBrains. It contains many of the primitives that enable advanced coroutines covered in this guide, including launch, as...

Kotlin Coroutine (1): Foundation and In-depth

First, access Second, the way of use Commonly used ways: CoroutineScope.launch() CoroutineScope.async() Third, about the exemplary example JOB is used to handle the level. For each created sweeper (vi...

Channel channel of the coroutine in Kotlin (1)

Channel channel of the coroutine in Kotlin (1) Channel-channel Channel capacity Iterate Channel Produce and Actor Channel's closure BroadcastChannel Channel-channel Channel is actually a secure queue,...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top