使用 lambda 传递代码、使用可以替换的合理默认值,使用 inline 扩展函数,将这些行为添加到现有 API 中,这种模式是 Android KTX 库提供的典型增强功能。
// 未使用 Android KTX 前实现模式sharedPreferences.edit()// create an Editor.putBoolean("key", value).apply()// write to disk asynchronously// Android KTX 模式// SharedPreferences.edit extension function signature from Android KTX - Core// inline fun SharedPreferences.edit(// commit: Boolean = false,// action: SharedPreferences.Editor.() -> Unit)// Commit a new value asynchronouslysharedPreferences.edit {putBoolean("key", value)}// Commit a new value synchronouslysharedPreferences.edit(commit =true){putBoolean("key", value)}
// Combine 2 ArraySets into 1.val combinedArraySet =arraySetOf(1,2,3)+arraySetOf(4,5,6)// Combine with numbers to create a new sets.val newArraySet = combinedArraySet +7+8
// Get a reference to the ViewModel scoped to this Fragmentval viewModel by viewModels<MyViewModel>()// Get a reference to the ViewModel scoped to its Activityval viewModel by activityViewModels<MyViewModel>()
classMyDestination:Fragment(){// Type-safe arguments are accessed from the bundle.val args by navArgs<MyDestinationArgs>()...override fun onViewCreated(view: View, savedInstanceState: Bundle?){view.findViewById<Button>(R.id.next).setOnClickListener {// Fragment extension added to retrieve a NavController from// any destination.findNavController().navigate(R.id.action_to_next_destination)}}...}
classMainViewModel:ViewModel(){// Make a network request without blocking the UI threadprivate fun makeNetworkRequest(){// launch a coroutine in viewModelScopeviewModelScope.launch {remoteApi.slowFetch()...}}// No need to override onCleared()}
classCoroutineDownloadWorker(context: Context, params: WorkerParameters):CoroutineWorker(context, params){overridesuspendfundoWork(): Result = coroutineScope {val jobs =(0 until 100).map{async {downloadSynchronously("https://www.google.com")}}// awaitAll will throw an exception if a download fails, which// CoroutineWorker will treat as a failurejobs.awaitAll()Result.success()}}