In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use kotlin to improve app performance. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
A collaborator is a concurrent design pattern that you can use on Android to simplify code that executes asynchronously. The Kotlin1.3 version adds Coroutines and is based on established concepts in other languages.
On Android, the collaboration process helps solve two main problems:
Manage long-running tasks, otherwise it may block the main thread and cause applications to freeze. Provide primary security, or securely invoke network or disk operations from the main thread.
This topic describes how to use the Kotlin protocol to solve these problems, so that you can write clearer, more concise application code.
Manage long-running tasks
On Android, each application has a main thread to process the user interface and manage user interaction. If your application allocates too much work to the main thread, the application may be significantly stuttered or slow. Web requests, JSON parsing, reading or writing from a database, or even just iterating over large lists can cause applications to run slowly, causing visible slow or frozen UI to respond slowly to touch events. These long-running operations should run outside the main thread.
The following example shows a simple collaborative implementation of a hypothetical long-running task:
Suspend fun fetchDocs () {/ / Dispatchers.Main val result = get ("https://developer.android.com") / / Dispatchers.IO for `get` show (result) / / Dispatchers.Main} suspend fun get (url: String) = withContext (Dispatchers.IO) {/ *... * /})
Collaborative programs build general functions by adding two operations to deal with long-running tasks. In addition to invoke (or call) and return, the collaborator adds suspend and resume:
Suspend suspends the execution of the current collaborative program and saves all local variables. The resume resumes the execution of the paused collaborative program from the paused synergy.
You can only call the suspend function from other suspend functions, or use a protocol builder such as startup to start a new one.
In the above example, get () is still running on the main thread, but it suspends the collaborator before initiating the network request. When the network request completes, get resumes the paused collaborator instead of using a callback to notify the main thread.
Kotlin uses a stack framework to manage functions that run with any local variables. When the collaborator is suspended, the current stack frame is copied and saved for later use. On restore, the stack frame will be copied back from the saved location, and the function will start running again. Even if the code looks like a normal sequential blocking request, the protocol ensures that the network request avoids blocking the main thread.
Use coroutines for main-safety
The Kotlin protocol uses a scheduler to determine which threads are used for execution of the program. To run the code outside the main thread, you can tell the Kotlin protocol to perform work on the Default or IO scheduler. In Kotlin, all collaborative programs must run in the scheduler, even if they are running on the main thread. Collaborative programs can be paused and the scheduler is responsible for resuming them. To specify where the collaborator should run, Kotlin provides three schedulers that can be used:
Dispatchers.Main-use this scheduler to run the collaborator on the main Android thread. This should only be used to interact with UI and perform fast work. Examples include calling pending functions, running Android UI framework operations, and updating LiveData objects. Dispatchers.IO-this scheduler has been optimized to perform disk or network I / O outside the main thread. Examples include using the Room component, reading or writing files, and running any network operation. Dispatchers.Default-this scheduler has been optimized to perform CPU-intensive work outside the main thread. Example use cases include sorting lists and parsing JSON.
Continuing with the previous example, you can use the scheduler to redefine the get function. Inside the body of the get, call withContext (Dispatchers.IO) to create a block that runs on the IO thread pool. Any code placed in this block is always executed through the IO scheduler. Because withContext itself is a pending function, the function get is also a pending function.
Using a collaborative program, you can schedule threads with fine-grained control. Because withContext () allows you to control the thread pool of any line of code without introducing a callback, you can apply it to very small functions, such as reading from a database or executing a network request. It is a good practice to use withContext () to ensure that each function is primary safe, which means that you can call the function from the main thread. In this way, the caller never has to think about which thread should be used to execute the function.
In the previous example, fetchDocs () executes on the main thread; however, it can safely call get, which executes the network request in the background. Because the co-program supports suspension and recovery, as long as the withContext block is completed, the collaboration on the main thread will resume as a result of get.
Important: using suspend does not tell Kotlin to run functions on background threads. It is normal for the pause function to run on the main thread. It is also common to start a collaborative program on the main thread. Always use withContext () within the suspend function when you need primary security, such as reading or writing to disk, performing network operations, or running CPU-intensive operations.
Compared to the equivalent callback-based implementation, withContext () does not add additional overhead. In addition, in some cases, the withContext () call can be optimized rather than based on an equivalent callback-based implementation. For example, if a function makes ten calls to the network, you can tell Kotlin to switch threads only once by using external withContext (). Then, even though the network library uses withContext () multiple times, it still stays on the same scheduler and avoids switching threads. In addition, Kotlin optimizes switching between Dispatchers.Default and Dispatchers.IO to avoid thread switching as much as possible.
Important: using a scheduler that uses thread pools such as Dispatchers.IO or Dispatchers.Default does not guarantee that the block executes on the same thread from top to bottom. In some cases, the Kotlin protocol may move execution to another thread after pausing and resuming. This means that thread local variables may not point to the same value of the entire withContext () block.
Specify CoroutineScope
When you define a collaborator, you must also specify its CoroutineScope. CoroutineScope manages one or more related collaborations. You can also use CoroutineScope to start a new collaboration process within this scope. However, unlike the scheduler, CoroutineScope does not run a collaborative program.
An important function of CoroutineScope is to stop the execution of the collaboration process when the user leaves the content area in the application. With CoroutineScope, you can ensure that any running operations are stopped correctly.
Using CoroutineScope with Android schema components
On Android, you can associate CoroutineScope implementations with component lifecycles. This avoids leaking memory or performing extra work for activity or fragment that are no longer relevant to the user. Using Jetpack components, they are naturally suitable for ViewModel. Because ViewModel is not destroyed during configuration changes, such as screen rotation, you don't have to worry about the collaborative program being canceled or restarted.
The scope knows every collaborative program they start. This means that you can cancel everything started in the scope at any time. The scope propagates itself, so if one collaborative program starts another, the two collaborative programs have the same scope. This means that even if other libraries start collaborations from your scope, you can cancel them at any time. This is especially important if you are running collaborative programs in ViewModel. If the ViewModel is destroyed because the user leaves the screen, all asynchronous work it is performing must be stopped. Otherwise, you will waste resources and may leak memory. If you should continue to work asynchronously after destroying the ViewModel, it should be done at a lower level of the application architecture.
Warning: cancel the collaborative program by throwing a CancellationException. An exception handler that catches an exception or Throwable is triggered during a co-program cancellation.
Using the KTX library components for the Android architecture, you can also use the extended property viewModelScope to create a collaborative program that can run until the ViewModel is destroyed.
Start a collaborative process.
You can start a collaborative program in one of two ways:
Launch starts a new collaborative process and does not return the result to the caller. Any work that is thought of as "launch and forget" can be started with launch. Async starts a new collaborative program and allows you to return results using a pending function called await.
In general, you should start a new protocol from a regular function, because a regular function cannot be called to wait. Asynchrony is used only when parallel decomposition is performed within another co-program or within a pending function.
Based on the previous example, here is a protocol with the viewModelScope KTX extension property that uses launch to switch from a regular function to a collaborative program:
Fun onDocsNeeded () {viewModelScope.launch {/ / Dispatchers.Main fetchDocs () / / Dispatchers.Main (suspend function call)}}
Warning: starting and asynchronously handling exceptions are different. Because async expects to eventually call await at some point, it will retain the exceptions and re-throw them in the await call. This means that if you use await to start a new collaborative program from a regular function, the exception may be silently removed. These discarded exceptions do not appear in crash metrics, nor in logcat.
Parallel decomposition
When the function returns, you must stop all collaborative programs started by the pending function, so you may need to ensure that these collaborations are completed before returning. Through structured concurrency in Kotlin, you can define a coroutineScope that starts one or more collaborative programs. Then, using await () (for a single co-program) or awaitAll () (for multiple collaborators), you can ensure that these collaborations are completed before they are returned from the function.
For example, let's define a coroutineScope that fetches two documents asynchronously. By calling await () on each deferred reference, we ensure that both asynchronous operations are completed before the return value:
Suspend fun fetchTwoDocs () = coroutineScope {val deferredOne = async {fetchDoc (1)} val deferredTwo = async {fetchDoc (2)} deferredOne.await () deferredTwo.await ()}
Even if fetchTwoDocs () starts new collaborative programs asynchronously, the function uses awaitAll () to wait for those started collaborative programs to finish before returning. Note, however, that even if we do not call awaitAll (), the coroutineScope builder will not resume the call to fetchTwoDocs until all the new ones are complete.
In addition, coroutineScope catches any exceptions thrown by the co-program and routes them back to the caller.
For more information about parallel decomposition, see Writing pending functions.
Architectural components with built-in support
Some architectural components, including ViewModel and Lifecycle, include built-in support for collaborative programs through their own CoroutineScope members. For example, ViewModel contains a built-in viewModelScope. This provides a standard way to start a collaborative program within the scope of ViewModel, as shown in the following example:
Class MyViewModel: ViewModel () {fun launchDataLoad () {viewModelScope.launch {sortList () / / Modify UI}} / * Heavy operation that cannot be done in the Main Thread * / suspend fun sortList () = withContext (Dispatchers.Default) {/ / Heavy work}} LiveData also uses a collaborative program with liveData blocks: liveData {/ / runs in its own LiveData-specific scope}
This is the end of this article on "how to use kotlin to improve app performance". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.