13
13
* See the License for the specific language governing permissions and
14
14
* limitations under the License.
15
15
*/
16
- package com.android.ai.samples.imagen
16
+ package com.android.ai.samples.imagen.data
17
17
18
18
import android.graphics.Bitmap
19
- import androidx.lifecycle.ViewModel
20
- import androidx.lifecycle.viewModelScope
21
19
import com.google.firebase.Firebase
22
20
import com.google.firebase.ai.ai
23
21
import com.google.firebase.ai.type.GenerativeBackend
@@ -26,25 +24,10 @@ import com.google.firebase.ai.type.ImagenGenerationConfig
26
24
import com.google.firebase.ai.type.ImagenImageFormat
27
25
import com.google.firebase.ai.type.PublicPreviewAPI
28
26
import javax.inject.Inject
29
- import kotlinx.coroutines.flow.MutableStateFlow
30
- import kotlinx.coroutines.flow.StateFlow
31
- import kotlinx.coroutines.launch
32
-
33
- sealed interface ImagenUIState {
34
- data object Initial : ImagenUIState
35
- data object Loading : ImagenUIState
36
- data class ImageGenerated (
37
- val bitmap : Bitmap ,
38
- val contentDescription : String ,
39
- ) : ImagenUIState
40
- data class Error (val message : String ) : ImagenUIState
41
- }
42
-
43
- class ImagenViewModel @Inject constructor() : ViewModel() {
44
-
45
- private val _uiState : MutableStateFlow <ImagenUIState > = MutableStateFlow (ImagenUIState .Initial )
46
- val uiState: StateFlow <ImagenUIState > = _uiState
27
+ import javax.inject.Singleton
47
28
29
+ @Singleton
30
+ class ImagenDataSource @Inject constructor() {
48
31
@OptIn(PublicPreviewAPI ::class )
49
32
private val imagenModel = Firebase .ai(backend = GenerativeBackend .vertexAI()).imagenModel(
50
33
modelName = " imagen-4.0-generate-preview-06-06" ,
@@ -56,21 +39,11 @@ class ImagenViewModel @Inject constructor() : ViewModel() {
56
39
)
57
40
58
41
@OptIn(PublicPreviewAPI ::class )
59
- fun generateImage (prompt : String ) {
60
- _uiState .value = ImagenUIState .Loading
61
-
62
- viewModelScope.launch {
63
- try {
64
- val imageResponse = imagenModel.generateImages(
65
- prompt = prompt,
66
- )
67
- val image = imageResponse.images.first()
68
-
69
- val bitmapImage = image.asBitmap()
70
- _uiState .value = ImagenUIState .ImageGenerated (bitmapImage, contentDescription = prompt)
71
- } catch (e: Exception ) {
72
- _uiState .value = ImagenUIState .Error (e.message ? : " Unknown error" )
73
- }
74
- }
42
+ suspend fun generateImage (prompt : String ): Bitmap {
43
+ val imageResponse = imagenModel.generateImages(
44
+ prompt = prompt,
45
+ )
46
+ val image = imageResponse.images.first()
47
+ return image.asBitmap()
75
48
}
76
49
}
0 commit comments