Firebase Android onAuthStateChanged called twice

前端 未结 6 1125
忘了有多久
忘了有多久 2020-12-02 20:16

I\'ve start working with new Firebase SDK.

When I\'m doing user login, I\'m onAuthStateChanged method is being called twice with same state (etc. user sign in).

6条回答
  •  我在风中等你
    2020-12-02 20:30

    While the other answers provided here might do the job, I find managing a flag cumbersome and error-prone.

    I prefer debouncing the event within short periods of time. It is very unlikely, maybe even impossible, for a user to login then logout within a period of 200ms let's say.

    TLDR

    Debouncing means that before handling an event, you wait to see if the same event is gonna fire again within a predefined period of time. If it did, you reset the timer and wait again. If it didn't, you handle the event.

    This is an Android question, which is not my field, but I'm sure android provides some kind of tool that can help with the task. If not, you can make one using a simple timer.

    Here's how a Javascript implementation might look like:

    var debounceTimeout;
    const DebounceDueTime = 200; // 200ms
    
    function onAuthStateChanged(auth)
    {
        if (debounceTimeout)
            clearTimeout(debounceTimeout);
    
        debounceTimeout = timeout(() =>
        {
            debounceTimeout = null;
    
            handleAuthStateChanged(auth);
        }, DebounceDueTime);
    }
    
    function handleAuthStateChanged(auth)
    {
        // ... process event
    }
    

提交回复
热议问题