• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 package com.android.wallpaper.picker.undo.ui.binder
19 
20 import android.app.Dialog
21 import android.widget.Toolbar
22 import androidx.lifecycle.Lifecycle
23 import androidx.lifecycle.LifecycleOwner
24 import androidx.lifecycle.lifecycleScope
25 import androidx.lifecycle.repeatOnLifecycle
26 import com.android.wallpaper.R
27 import com.android.wallpaper.picker.common.dialog.ui.viewbinder.DialogViewBinder
28 import com.android.wallpaper.picker.common.dialog.ui.viewmodel.DialogViewModel
29 import com.android.wallpaper.picker.undo.ui.viewmodel.UndoViewModel
30 import kotlinx.coroutines.launch
31 
32 object RevertToolbarButtonBinder {
33     /** Binds the given view to the given view-model. */
34     fun bind(
35         view: Toolbar,
36         viewModel: UndoViewModel,
37         lifecycleOwner: LifecycleOwner,
38     ) {
39         val menuItem = view.menu.findItem(R.id.revert)
40         menuItem.setOnMenuItemClickListener {
41             viewModel.onRevertButtonClicked()
42             true
43         }
44 
45         var dialog: Dialog? = null
46 
47         fun showDialog(viewModel: DialogViewModel) {
48             dialog =
49                 DialogViewBinder.show(
50                     context = view.context,
51                     viewModel = viewModel,
52                 )
53             dialog?.show()
54         }
55 
56         fun dismissDialog() {
57             dialog?.setOnDismissListener(null)
58             dialog?.dismiss()
59             dialog = null
60         }
61 
62         lifecycleOwner.lifecycleScope.launch {
63             lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
64                 launch { viewModel.isRevertButtonVisible.collect { menuItem.isVisible = it } }
65 
66                 launch {
67                     viewModel.dialog.collect { dialogViewModel ->
68                         if (dialogViewModel != null) {
69                             dismissDialog()
70                             showDialog(dialogViewModel)
71                         } else {
72                             dismissDialog()
73                         }
74                     }
75                 }
76             }
77         }
78     }
79 }
80