how to properly initialize firebase app that can be used more than once?

一世执手 提交于 2021-01-29 21:59:00

问题


usually I initialize firebase in my activity just like this

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // usually initializing firebase just like this
        FirebaseApp.initializeApp(this)

}

but now I need that firebaseApp to be passed to get FirebaseStorage instance like this:

    // set firebase option
    val optionBuilder = FirebaseOptions.Builder()
    optionBuilder.setStorageBucket("newBucket")
    val firebaseOption = optionBuilder.build()

    // initialize firebase app
    val app = FirebaseApp.initializeApp(this,firebaseOption)

    // create reference, pass app to firebase storage
    val storageRef = FirebaseStorage.getInstance(app).reference.child("profilePicture")

but the problem is.....

I need to create that firebase storage reference in more than one place. so how how to properly initialize firebase app so that I can use it in more than one place ?

do I need to initialize it in MainActivity AND recreate it again whenever I need to make storage reference ? it seems like a bad idea, but I don't know .... please help :)


回答1:


Just initialize it once and store it in a place where they can all access it - a singleton.



来源:https://stackoverflow.com/questions/60291630/how-to-properly-initialize-firebase-app-that-can-be-used-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!