Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize lazy loading in Kotlin

Shulou Source: shulou.com Published: 2022-06-01 04:24:30 10月04日 Update

This article mainly introduces Kotlin how to achieve lazy loading, the article introduces in great detail, has a certain reference value, interested friends must read it!

Lazy Loading (lazy load)

Delayed loading has several benefits. Delayed loading makes the program start faster because loading is deferred until the variable is accessed. This is particularly useful in Android applications that use Kotlin instead of server applications. For Android applications, we naturally want to reduce the application startup time so that users can see the application content faster instead of waiting for the initial load screen.

Lazy loading is also more efficient memory, because we only need to invoke resources to load resources into memory. For example:

Val gankApi: GankApi by lazy {val retrofit: Retrofit = Retrofit.Builder () .baseUrl (API_URL) .addConverterFactory (MoshiConverterFactory.create ()) .build () retrofit.create (GankApi::class.java)}

If the user has never called GankApi, it will never be loaded. Therefore, it will not take up the required resources.

Of course, lazy loading can also be used for encapsulation initialization:

Val name: String by lazy {Log.d (TAG, "executed only first time") "Double Thunder"}

If you are not worried about multithreading or want to improve more performance, you can also use the

Lazy (LazyThreadSafeMode.NONE) {.} above is all the content of this article "how to achieve lazy loading in Kotlin". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Applications content programs resources memory applications time more faster users articles delays valid never value interests variables benefits guys buddies Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia MariaDB Linux Huawei